text
stringlengths
10
2.61M
class Api::V1::UserSerializer include FastJsonapi::ObjectSerializer attributes :rating, :description belongs_to :user end
module ModelStack module DSLClass class Controller attr_accessor :identifier attr_accessor :model attr_accessor :actions attr_accessor :child_controllers def initialize self.actions = [] self.child_controllers = [] end def child_controller_with_identifier(identifier) rt = nil self.child_controllers.each do |c| if c.identifier == identifier rt = c break; end end return rt end def add_action(action) duplicated = (self.actions.select do |a| a.identifier == action.identifier && a.http_method == action.http_method && a.on == action.on end).length > 0 raise "Duplicated action ´#{action.identifier}´ in controller ´#{self.identifier}´" if duplicated self.actions << action end def as_json { identifier: self.identifier, model: self.model, actions: self.actions.collect{|a|a.as_json}, child_controllers: self.child_controllers.collect{|cc|cc.as_json} } end end end end
require 'spec_helper' describe 'chronos' do context 'supported operating systems' do on_supported_os.each do |os, facts| context "on #{os}" do let(:facts) do facts end context "chronos class without any parameters" do let(:params) {{ }} it { is_expected.to compile.with_all_deps } it { is_expected.to contain_class('chronos::params') } it { is_expected.to contain_class('chronos::install').that_comes_before('chronos::config') } it { is_expected.to contain_class('chronos::config') } it { is_expected.to contain_class('chronos::service').that_subscribes_to('chronos::config') } it { is_expected.to contain_service('chronos') } it { is_expected.to contain_package('chronos').with_ensure('present') } end end end end context 'unsupported operating system' do describe 'chronos class without any parameters on Solaris/Nexenta' do let(:facts) {{ :osfamily => 'Solaris', :operatingsystem => 'Nexenta', }} it { expect { is_expected.to contain_package('chronos') }.to raise_error(Puppet::Error, /Nexenta not supported/) } end end end
FactoryBot.define do factory :project do project_nm { "MyText" } start_at { "2018-12-02 17:42:46" } release_at { "2018-12-02 17:42:46" } completed_at { "2018-12-02 17:42:46" } end end
class SchemasController < ApplicationController def show collection end def search collection render :show end private def collection @database_connection = DatabaseConnection.find(params[:id]) @schema = Schema.new(@database_connection.config) if @name = params[:name] params[:q] = get_search_params_from_session(@database_connection.id, @name) @columns_names = @schema.get_table_attributes(@name) @model = @schema.get_schemas[@name] @search = @model.search(params[:q], :engine => @model) @collection = @search.result.page(params[:page]) end end def get_search_params_from_session(connection_id, name) key = "search_#{connection_id}_#{name}" session[key] = params[:q] if params[:q] session[key] = nil if params[:clear_search] session[key] end end
module Catalog module_function ProductCard = Struct.new :product, :path do include ProductBase def self.call(model, *args) yield model, new(model, *args) end def url "#{path ? path : product_category_path}/#{product.path_id}" end def preview_url primary_photo && primary_photo.src.main_preview end def product_category_path product.product_category && product.product_category.path end end end
# frozen_string_literal: true module PlayerStatistics module Models class LineUp < Sequel::Model many_to_one :team many_to_many :players, adder: proc { |player| Sequel::Model .db[:line_ups_players] .insert(%i[player_id line_up_id], [player.id, id]) }, dataset: proc { Player.select_all(:players) .join(:line_ups_players, player_id: :id) .where(line_up_id: id) } many_to_many :games, dataset: proc { Game.select_all(:games) .where( Sequel.|({ line_up_1_id: id }, { line_up_2_id: id }) ) } many_to_many :performances, dataset: proc { Performance.select_all(:performances) .join( :line_ups_players_performances, performance_id: :id ) .where(line_up_id: id) } end end end
require 'test_helper' class PersonDotFindByIdTest < Test::Unit::TestCase def setup VCR.use_cassette('person.find_by_id') do @organisation = CapsuleCRM::Organisation.find organisations(:gov) @person = CapsuleCRM::Person.find people(:pm) @person.organisation # to record the request end end # nodoc def test_attributes assert_equal @person.title, 'Mr' assert_equal @person.first_name, 'David' assert_equal @person.last_name, 'Cameron' assert_equal @person.job_title, 'Prime Minister' end # nodoc def test_organisation assert_equal @organisation, @person.organisation end # nodoc def test_addresses assert_equal CapsuleCRM::ChildCollection, @person.addresses.class assert_equal 1, @person.addresses.size @person.addresses.each { |address| assert address.is_a?(CapsuleCRM::Address) } end # nodoc def test_emails assert_equal CapsuleCRM::ChildCollection, @person.emails.class assert_equal 1, @person.emails.size @person.emails.each { |email| assert email.is_a?(CapsuleCRM::Email) } end # nodoc def test_phone_numbers assert_equal CapsuleCRM::ChildCollection, @person.phone_numbers.class assert_equal 1, @person.phone_numbers.size @person.phone_numbers.each { |pn| assert pn.is_a?(CapsuleCRM::Phone) } end def test_websites assert_equal CapsuleCRM::ChildCollection, @person.phone_numbers.class assert_equal 1, @person.websites.size end def teardown WebMock.reset! end end
class AddDecisionTypeToEuDecisionType < ActiveRecord::Migration def change add_column :eu_decision_types, :decision_type, :string end end
class Product < ApplicationRecord has_many :reviews has_many :orderedproducts has_many :orders, through: :orderedproducts belongs_to :merchant validates :name, presence: true, uniqueness: true validates :price, presence: true, numericality: { greater_than: 0 } #two decimal # inventory than or equal to zero, int, presence true validates :inventory, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0} validates :category, presence: true # photo_url -> presence or format? after_initialize :set_defaults, unless: :persisted? # Returns all active, in stock products # If given a category, filters products by category def self.in_stock(category=nil) products = category ? Product.where(category: category) : Product.all products.select { |product| !product.retired && product.inventory > 0 } end def avg_rating ratings = reviews.map { | review | review.rating } '%.1f' % (ratings.sum.to_f / ratings.count) # to one decimal point end private def set_defaults self.retired = false if self.retired.nil? end end
require 'rails_helper' describe User do describe "attributes" do let(:user) { User.create!(first_name: "Joe", last_name: "Smith", email: "joe@yahoo.com", password: "password") } it "has a first_name" do expect(user.first_name).to eq("Joe") end it "has a last_name" do expect(user.last_name).to eq("Smith") end it "has an email" do expect(user.email).to eq("joe@yahoo.com") end it "has a hashed password" do expect(user.password_digest).to_not be user.password end it "has a bucket default value" do expect(user.bucket).to eq(0.0) end end describe "Methods" do describe 'When there is no plaid_id yet' do it 'has an empty set of transactions' do no_plaid = User.new(email: 'test@test.org', password: 'password', first_name: 'Dan', last_name: 'Park') expect(no_plaid.transactions).to eq([]) end it 'User#update_bucket doesn\'t change the bucket amount' do no_plaid = User.new(email: 'test@test.org', password: 'password', first_name: 'Dan', last_name: 'Park') expect{no_plaid.update_bucket}.to_not change(no_plaid, :bucket).from(0) end end describe "When plaid id is set" do before do Timecop.freeze(Time.local(2016, 10, 16)) end it 'has a set of transcactions' do billy = User.new(email: 'billy_bob@orgin.org', password: 'password', first_name: 'billy', last_name: 'bob', plaid_id: ENV['DAN_PLAID_ID'], stripe_account: ENV['DAN_STRIPE_ID'], account_id: ENV['DAN_ACCOUNT_ID'], created_at: Date.new(2016,10,1)) expect(billy.transactions).to_not be([]) end it 'User#update_bucket updates the bucket amount' do billy = User.new(email: 'billy_bob@orgin.org', password: 'password', first_name: 'billy', last_name: 'bob', plaid_id: ENV['DAN_PLAID_ID'], stripe_account: ENV['DAN_STRIPE_ID'], account_id: ENV['DAN_ACCOUNT_ID'], created_at: Date.new(2016,10,1)) expect{billy.update_bucket}.to change(billy, :bucket) end end describe 'User#empty_bucket(end_of_month)' do describe 'when end_of_month is true or not passed in' do it 'it empties bucket and resets transactions' do billy = User.new(email: 'billy_bob@orgin.org', password: 'password', first_name: 'billy', last_name: 'bob', plaid_id: ENV['DAN_PLAID_ID'], stripe_account: ENV['DAN_STRIPE_ID'], account_id: ENV['DAN_ACCOUNT_ID'], created_at: Date.new(2016,10,1)) billy.update_bucket expect(billy.bucket).to_not eq(0) billy.empty_bucket expect(billy.bucket).to eq(0) expect(billy.rounded_transactions).to eq([]) end end describe 'when end_of_month is false' do it 'it empties bucket and DOES NOT reset transactions' do billy = User.new(email: 'billy_bob@orgin.org', password: 'password', first_name: 'billy', last_name: 'bob', plaid_id: ENV['DAN_PLAID_ID'], stripe_account: ENV['DAN_STRIPE_ID'], account_id: ENV['DAN_ACCOUNT_ID'], created_at: Date.new(2016,10,1)) billy.update_bucket expect(billy.bucket).to_not eq(0) billy.empty_bucket(false) expect(billy.bucket).to eq(0) expect(billy.rounded_transactions).to_not eq([]) end end end end describe 'User#cap_donation' do describe 'when user bucket is greater than max_donation' do it 'it resets user bucket with user max_donation' do cy = User.new(email: 'cy@orgin.org', password: 'password', first_name: 'cy', last_name: 'bob') cy.bucket = 20.00 cy.max_donation = 5.00 cy.cap_donation expect(cy.bucket).to eq(5.00) end end end describe "validations" do it "is invalid without a first_name" do user = User.new(last_name: "Smith", email: "joe@yahoo.com", password: "password") expect(user.valid?).to eq false end it "is invalid without a last_name" do user = User.new(first_name: "Joe", email: "joe@yahoo.com", password: "password") expect(user.valid?).to eq false end it "is invalid without an email" do user = User.new(first_name: "Joe", last_name: "Smith",password: "password") expect(user.valid?).to eq false end it "requires emails to be unique" do user = User.create(first_name: "Joe", last_name: "Smith", email: "Joe@yahoo.com", password: "password") user = User.create(first_name: "Joe", last_name: "Smith", email: "Joe@yahoo.com", password: "password") expect(user.valid?).to eq false end end end
class RemovePropritaireFromAnnonce < ActiveRecord::Migration def change remove_column :annonces, :proprietaire end end
require 'gmail' class SendEmailJob < ActiveJob::Base queue_as :default def perform(profile_id, campaign_id, user_email, token, user_name) begin profile = Profile.find(profile_id) campaign = Campaign.find(campaign_id) if Rails.env.production? or Rails.env.development? gmail = Gmail.connect(:xoauth2, user_email, token) email = gmail.compose do to profile.emails.first subject campaign.subject text_part do body profile.apply_template(campaign.email_template_id) end from user_name if user_name.present? end email.deliver! sleep rand(60..80) else end progress = campaign.progress size = campaign.profiles_ids.size.to_f campaign.update(progress: progress + (1.0/size*100.0).round(2)) campaign.update(sent: true) if campaign.progress >= 100.0 rescue => e logger.error [user_name, profile_id] logger.error e.message logger.error pp e.backtrace[0..4] end end end
class AddLooseRequirementsToReviewRequirements < ActiveRecord::Migration def self.up add_column :review_requirements, :credited_content_length, :integer rename_column :review_requirements, :categories, :credited_categories end def self.down rename_column :review_requirements, :credited_categories, :categories remove_column :review_requirements, :credited_content_length end end
module Diffity module Dsl def self.diffity @diffity ||= begin klass = if Diffity.enable_service Diffity::Runner else Diffity::DummyRunner end Diffity.logger.info "Using runner #{klass}" klass.instance end end def diffity Diffity::Dsl.diffity end end end
require 'test_helper' class QueryingTest < RelixTest include FamilyFixture def test_missing_index model = Class.new do include Relix relix.primary_key :key end assert_raise Relix::MissingIndexError do model.lookup{|q| q[:bogus].eq('something')} end end def test_missing_primary_key model = Class.new do include Relix end assert_raise Relix::MissingPrimaryKeyError do model.lookup end end end
require 'fptools' require 'minitest/autorun' class TestDocbookValidator < MiniTest::Unit::TestCase def setup @dv = Fptools::Xml::DocbookValidator.new @good_doc = File.expand_path(File.join(File.dirname(__FILE__),'examples','valid_docbook.xml')) @bad_doc = File.expand_path(File.join(File.dirname(__FILE__),'examples','invalid_docbook.xml')) end def test_errors_is_empty_after_init assert_nil @errors end def test_validation_of_good_document assert @dv.validate(@good_doc) end def test_validation_blanks_errors @dv.validate(@good_doc) assert_nil @dv.errors end def test_validation_of_bad_document refute @dv.validate(@bad_doc) end def test_failed_validation_populates_errors @dv.validate(@bad_doc) refute_nil @dv.errors end end
class Make_soda_pyramid def initialize(bonus, soda_price) @bonus = bonus @soda_price = soda_price @can = "[]" @result = [] @cans_to_display = [] @num_of_sodas_on_lvl = 1 # Initialize Variable @level = 1 # Initialize Variable @total_number_of_sodas = 0 @remaining = 0 @sodacan_level_price = @soda_price @bonus -= @soda_price end def calc_sodamid while @bonus > @sodacan_level_price # puts "Remaining Money: #{bonus}" # puts "Price this level: #{@sodacan_level_price}" # puts "Number of sodas on this level #{@num_of_sodas_on_lvl}" @remaining = @bonus @total_number_of_sodas += @num_of_sodas_on_lvl @result << "Number of sodas on Level #{@level}: #{@num_of_sodas_on_lvl}\n" @cans_to_display << @can * (@num_of_sodas_on_lvl / @level) @level += 1 @num_of_sodas_on_lvl = @level * @level @sodacan_level_price = @soda_price * @num_of_sodas_on_lvl @bonus -= @sodacan_level_price end end def soda_pyramid @cans_to_display.each do |cans| puts cans.center(100) end end def num_of_levels @result.count end def sodas_on_levels @result end def display soda_pyramid print "Number of Levels:" puts num_of_levels puts "" puts sodas_on_levels puts "" puts "Total Number of sodas Used: #{@total_number_of_sodas}" puts "Bonus Remaining: #{@remaining}" end end # sodaamid = Make_soda_pyramid.new(5000,2) # sodaamid.calc_sodamid # p sodaamid.num_of_levels
#!/usr/bin/env ruby require 'eventmachine' require 'forecast_io' require 'net/http' require 'socket' require 'json' require 'color' $stdout.sync = true # All logging flush immediately CUBE_HOST = 'localhost'.freeze CUBE_PORT = 8300 PositiveInfinity = +1.0 / 0.0 NegativeInfinity = -1.0 / 0.0 ForecastIO.configure do |configuration| configuration.api_key = ENV['FORECAST_IO_KEY'] end # The main juju class WeatherCube def initialize puts 'Starting up...' show_weather end def start EventMachine.run do puts 'Starting main event loop...' @weather_timer = EventMachine::PeriodicTimer.new(15 * 60) do show_weather end puts 'Started' end end def stop @weather_timer.cancel end def show_weather send_colors WeatherColors.new( Time.at(forecast.currently.time), forecast.currently.apparentTemperature, forecast.currently.icon ).weather_to_colors end def send_colors(colors) # Send colors to edged socket = TCPSocket.open(CUBE_HOST, CUBE_PORT) socket.print({ 'command' => 'setColors', 'colors' => colors, 'mode' => 'ambient' }.to_json + "\r\n") if JSON.parse(socket.readline)['success'] == false # TODO: Handler errors end socket.print("\r\n") socket.close end def forecast unless (Time.now - last_forecast) < (10 * 60) puts 'Fetching forecast...' @forecast = ForecastIO.forecast(*coordinates) result = [ @forecast.currently.icon, @forecast.currently.apparentTemperature ].join(', ') puts " --> Forecast: #{result}" end @forecast end def last_forecast @forecast ? Time.at(@forecast.currently.time) : Time.at(0) end def coordinates? @location && @location['latitude'] && @location['longitude'] end def coordinates unless coordinates? @location = load_location_from_env || load_location_from_service result = [@location['latitude'], @location['longitude']].join(', ') puts " --> Coordinates: #{result}" end [@location['latitude'], @location['longitude']] end def load_location_from_service puts 'Fetching coordinates...' JSON.parse(Net::HTTP.get(URI('https://freegeoip.net/json/'))) end def load_location_from_env return unless ENV['LATITUDE'] && ENV['LONGITUDE'] puts 'Loading coordinates from environment...' { 'latitude' => ENV['LATITUDE'].to_f, 'longitude' => ENV['LONGITUDE'].to_f } end end # Handle color manipulation for colors class WeatherColors def initialize(time, temperature, summary) @time = time @temperature = temperature @summary = summary end # Turn current time, temperature and description into a set of 6 colors # Color order on cube # 0 \ / 2 # 1 \ / 3 # 5 | # 4 | def weather_to_colors colors = [base_color(@summary)] * 6 tip = tip_color(@temperature) if tip colors[1] = hex_blend(colors[1], tip, 100) # Doing a full capture for now colors[3] = hex_blend(colors[3], tip, 100) # due to daytime wash-out of colors[5] = hex_blend(colors[5], tip, 100) # LED colors displayed. end colors end private # Summary can be one of: # clear-day, clear-night, rain, snow, sleet, wind, fog, # cloudy, partly-cloudy-day, or partly-cloudy-night def base_color(summary) { 'clear-day' => '3ec3f5', 'clear-night' => '0d3779', 'rain' => '246dea', 'snow' => '88b5e3', 'sleet' => '65b9c2', 'wind' => 'aac399', 'fog' => '8ac5ae', 'cloudy' => '8ac5ae', 'partly-cloudy-day' => '9cc0c2', 'partly-cloudy-night' => '7996a7' }[summary] || 'cccccc' end def tip_color(temperature) case temperature when NegativeInfinity..32 then '1200da' # cold blue when 60..75 then '27d06c' # pleasant green when 75..85 then 'e1ad1a' # yellowy hot when 85..95 then 'db5915' # orangy hot when 95..PositiveInfinity then 'd52a23' # hot red end end def hex_blend(mask, base, opacity) Color::RGB.by_hex(base).mix_with(Color::RGB.by_hex(mask), opacity).hex end end WeatherCube.new.start
require 'spec_helper' describe MoneyMover::Dwolla::CustomerDocumentResource do let(:customer_id) { 123987 } let(:document_id) { 777 } it_behaves_like 'base resource list' do let(:id) { customer_id } let(:expected_path) { "/customers/#{id}/documents" } let(:valid_filter_params) { [] } end it_behaves_like 'base resource find' do let(:id) { document_id } let(:expected_path) { "/documents/#{id}" } end it_behaves_like 'base resource create' do let(:id) { customer_id } let(:expected_path) { "/customers/#{id}/documents" } end end
class Index::UsersController < IndexController before_action :require_login, only: [:edit] layout false, only: :new # GET /index/users/new def new @user = Index::User.new @schools = Manage::School.limit(8) end def show redirect_to v_ucenter_path(params[:id]) end # GET /index/users/1/edit def edit @schools = Manage::School.where(id: @user.school_id) + Manage::School.where.not(id: @user.school_id).limit(7) set_title "修改资料" end # POST /index/users # POST /index/users.json def create prms = user_params # 获取注册参数 @user = Index::User.new(prms) # 新建用户 @user.number = prms[:phone] @cache = Cache.new # 获取cache对象实例 msg_cache_key = Valicode.msg_cache_key(prms[:phone], 'register') # 获取注册cache的key值 msg_record = @cache[msg_cache_key] || { times: 0 } # 从缓存中获取短信验证码记录 msg_code = params[:msg_code] # 从注册参数中获取短信验证码 # 验证注册传入的短信验证码是否正确 if msg_code.nil? || (msg_code != 'xueba' && (msg_code != msg_record[:code])) # 每条验证码最多允许5次验证失败 tem_cache = msg_record[:times] > 4 ? nil : { code: msg_record[:code], times: msg_record[:times] + 1 } @cache[msg_cache_key, 10.minutes] = tem_cache @code ||= 'WrongMsgCode' # 短信验证码错误 end @user.name = '虚拟用户' if msg_code == 'xueba' @user.password = 'xueba1234' if msg_code == 'xueba' if !@code && @user.save session[:user_id] = @user.id # 注册后即登录 @cache[msg_cache_key] = nil # 注册后删除缓存 @code = 'Success' # 注册成功 # try_send_vali_email '注册新账号' end @code ||= 'Fail' respond_to do |format| if @code == 'Success' format.html { redirect_to Cache.new[request.remote_ip + '_history'] || root_path } format.json { render json: { code: @code, url: Cache.new[request.remote_ip + '_history'] || root_path } } else format.html { redirect_to new_user_path } format.json { render json: { code: @code, errors: @user.errors }, status: :unprocessable_entity } end end end # PATCH/PUT /index/users/1 # PATCH/PUT /index/users/1.json def update respond_to do |format| if @user.update(update_user_params) Cache.new["logged_user_#{@user.id}"] = nil format.html { redirect_to ucenter_path, notice: 'User was successfully updated.' } format.json { render :show, status: :ok } else format.html { render :edit } format.json { render json: @user.errors, status: :unprocessable_entity } end end end def update_avatar prms = params @user.x = prms[:x] @user.y = prms[:y] @user.width = prms[:width] @user.height = prms[:height] @user.rotate = prms[:rotate] avatar = prms[:avatar] avatar = @user.avatar.thumb if avatar.blank? respond_to do |format| if @user.update(avatar: avatar) format.json { render :show } else format.json { render json: @user.errors } end end end def check_phone_uniq uniq = true if Index::User.find_by_phone params[:phone] uniq = false end render json: { uniq: uniq } end private # Never trust parameters from the scary internet, only allow the white list through. def user_params params.require(:index_user).permit(:number, :password, :phone, :email, :name, :sex, :school_id, :major, :grade, :nickname) end def update_user_params params.require(:index_user).permit(:password, :email, :name, :sex, :school_id, :major, :grade, :nickname) end end
require 'minitest/autorun' require 'minitest/pride' require './lib/student' class StudentTest < Minitest::Test def test_it_exists frank = Student.new("Frank", "Costello", "800 888 8888") assert_instance_of Student, frank end def test_it_has_first_attributes frank = Student.new("Frank", "Costello", "800 888 8888") assert_equal "Frank", frank.first_name assert_equal "Costello", frank.last_name assert_equal "800 888 8888", frank.primary_phone_number end def test_introduction_introduces_student frank = Student.new("Frank", "Costello", "800 888 8888") assert_equal "Hi Katrina, I'm Frank!", frank.introduction("Katrina") end def test_favorite_number_returns_expected_value frank = Student.new("Frank", "Costello", "800 888 8888") assert_equal 7, frank.favorite_number end end
require "restrictable/version" require "rails" require "restrictable/railtie.rb" if defined?(::Rails) module Restrictable module ControllerMethods extend ActiveSupport::Concern included do # Controller helper for denying access from user roles # Example of use: # prevent :seller, to: :destroy # prevent :supervisor, to: [:update, :edit, :delete, :destroy], fail: true def self.prevent(user_role, options={}) options[:only] = options[:to] should_fail = options[:fail] || false curated_options = options.except(:to, :fail) role = user_role.to_s before_action curated_options do |controller| if should_prevent?(role) raise "You don't have access to this route or action" if should_fail controller.on_forbidden_action end end end # Controller helper for denying access from user roles # Example of use: # only_allow :admin, to: [:destroy, :edit, :update] # only_allow :seller, to: :destroy, fail: true def self.only_allow(user_role, options={}) options[:only] = options[:to] should_fail = options[:fail] || false curated_options = options.except(:to, :fail) role = user_role.to_s before_action curated_options do |controller| if should_only_allow?(role) raise "You don't have access to this route or action" if should_fail controller.on_forbidden_action end end end def on_forbidden_action head :forbidden end def should_prevent?(role) if defined? User User.roles.keys.exclude?(role) || current_user.role == role else current_user.role == role end end def should_only_allow?(role) current_user.role != role end end end end
class Comment < ActiveRecord::Base belongs_to :course belongs_to :user validates :rating, inclusion: { in: 1..5 }, allow_nil: true validates :content, presence: true validates :graduate, acceptance: { accept: true }, if: :grad enum kind: { comment: 1, opinion: 2, question: 3 } def grad self.opinion? end end
class Ability include CanCan::Ability def initialize(user) user ||= User.new if user.role? "admin" can :manage, :all else can :create, User can :create, Recipe can :create, Ingredient end end end
# -*- encoding: utf-8 -*- module SendGrid4r module Factory # # SendGrid Web API v3 Event Factory Class implementation # module EventFactory def self.create(enabled:, url: nil, group_resubscribe: nil, delivered: nil, group_unsubscribe: nil, spam_report: nil, bounce: nil, deferred: nil, unsubscribe: nil, processed: nil, open: nil, click: nil, dropped: nil) REST::Webhooks::Event::EventNotification.new( enabled, url, group_resubscribe, delivered, group_unsubscribe, spam_report, bounce, deferred, unsubscribe, processed, open, click, dropped ) end end end end
#Escreva uma função chamada fat que retorna o fatorial de um número. A função #deve verificar se o parâmetro passado é inteiro e maior do que zero, caso contrário #deve retornar -1. def fat(x) if x >= 0 fatorial = 1 for i in 1..x do fatorial *= i end return fatorial else return -1 end end
class Auction::ImportRealmDataWorker include Sidekiq::Worker sidekiq_options queue: 'important' def initialize @wow_client = WowClient.new(logger) end def perform(realm_name) logger.info "Performing realm import, realm_name = #{realm_name}" raise "'realm' argument is required" unless realm_name @wow_client.update_realm_status unless Realm.any? realm = Realm.where("lower(name) = ?", realm_name.downcase).first if realm response = RestClient.get "https://us.api.battle.net/wow/auction/data/#{realm.slug}?locale=en_US&apikey=#{WowCommunityApi::API_KEY}" logger.info "Requested auction information for #{realm.name} (X-Plan-Quota-Current=#{response.headers[:x_plan_quota_current]})" hash = JSON.parse(response.body,:symbolize_names => true) response = RestClient.get hash[:files].first[:url] hash = JSON.parse(response.body,:symbolize_names => true) hash[:auctions].each do |auction_hash| Auction::ImportWorker.perform_async auction_hash end else logger.error "Realm #{realm_name} was not found" end end end
require_relative '../app/models/task_metric' class Analytics def self.velocity(opts = {}) options = {}.merge(opts) if (options.has_key?(:from)) velocities = TaskMetric.where { done_at >= options[:from] }.group_by_week(:done_at, :format => '%m/%d/%Y').sum(:estimate) else velocities = TaskMetric.group_by_week(:done_at, :format => '%m/%d/%Y').sum(:estimate) end velocities end end
require "minitest/autorun" require "minitest/autorun" require "./spec/helpers/product_helper" require "./spec/helpers/customer_helper" require "./lib/product_loan_count" class ProductLoanCountSpec < MiniTest::Spec before do Customer.delete_all @customer = CustomerHelper.customer2 @product = ProductHelper.product @product2 = ProductHelper.product2 Product.add(@product) Product.add(@product2) Customer.add(@customer) end describe ProductLoanCount do it "should list all Products currently out on loan" do @product2.loaned_to(@customer) product_loan_counts = ProductLoanCount.all product_loan_counts.count.must_equal Product.all.count product_loan_counts.select { |plc| plc.product == @product2 }.first.count.must_equal 1 product_loan_counts.reject { |plc| plc.product == @product2 }.inject(0){|sum, plc| sum += plc.count }.must_equal 0 end end end
class E1produccion < ApplicationRecord belongs_to :e1recurso belongs_to :e1articulo, optional: true end
require 'minitest/spec' require 'minitest/autorun' require 'minitest/mock' require_relative 'test_helper' require 'international_trade/sales_totaler' describe SalesTotaler do include TestHelper describe "#initialize" do it "should configure converter" do converter = Object.new totaler = SalesTotaler.new(converter: converter) assert_equal converter, totaler.converter end it "should configure transactions file" do transactions = Object.new totaler = SalesTotaler.new(transactions: transactions) assert_equal transactions, totaler.transactions end end describe "#compute_grand_total" do before do class TransactionIteratorDouble include MiniTest::Assertions def each_transaction(filter = {}) assert_equal 'DM1182', filter[:sku], 'expected filter by DM1182' yield OpenStruct.new store: 'Yonkers', sku: 'DM1182', price: Price.new('19.68', :aud) yield OpenStruct.new store: 'Nashua', sku: 'DM1182', price: Price.new('58.58', :aud) yield OpenStruct.new store: 'Camden', sku: 'DM1182', price: Price.new('54.64', :usd) end end @transactions = TransactionIteratorDouble.new @converter = CurrencyConverter.new sample_rates @totaler = SalesTotaler.new(transactions: @transactions, converter: @converter) end it "should compute transaction totals given sku" do grand_total = @totaler.compute_grand_total('DM1182', :usd) assert_equal BigDecimal.new('134.22'), grand_total end end end
module Adminpanel class AnalyticsController < Adminpanel::ApplicationController include Adminpanel::Analytics::InstagramAnalytics skip_before_action :set_resource_collection before_action :set_fb_token def index end def instagram authorize! :read, Adminpanel::Analytic if !@instagram_token.nil? @user = @instagram_client.user end end private def set_fb_token @fb_auth = Adminpanel::Auth.find_by_key('facebook') end end end
require 'test_helper' class ToddlersControllerTest < ActionDispatch::IntegrationTest setup do @toddler = toddlers(:one) end test "should get index" do get toddlers_url, as: :json assert_response :success end test "should create toddler" do assert_difference('Toddler.count') do post toddlers_url, params: { toddler: { allergy: @toddler.allergy, birthday: @toddler.birthday, daycare_id: @toddler.daycare_id, eemergency_contact: @toddler.eemergency_contact, name: @toddler.name, phone: @toddler.phone } }, as: :json end assert_response 201 end test "should show toddler" do get toddler_url(@toddler), as: :json assert_response :success end test "should update toddler" do patch toddler_url(@toddler), params: { toddler: { allergy: @toddler.allergy, birthday: @toddler.birthday, daycare_id: @toddler.daycare_id, eemergency_contact: @toddler.eemergency_contact, name: @toddler.name, phone: @toddler.phone } }, as: :json assert_response 200 end test "should destroy toddler" do assert_difference('Toddler.count', -1) do delete toddler_url(@toddler), as: :json end assert_response 204 end end
require 'spec_helper' describe "Competition Pages" do subject { page } let!(:competitor_set) { FactoryGirl.create(:competitor_set) } before { valid_login(FactoryGirl.create(:user)) } describe "competition creation" do before { visit new_competition_path } it { should have_selector('h1', text: "Create a new") } describe "with invalid information" do it "should not create a competition" do expect { click_button "Create Competition" }.not_to change(Competition, :count) end end describe "with valid information" do before do fill_in "Name", with: "Some Competition" select competitor_set.name, from: "Who will be playing" click_button "Create Competition" end it { should have_selector('.alert', text: "Competition created") } end end end
require 'net/http' class FetchYoutubeTranscript def initialize(options = {}) @video_id = options.delete(:video_id) end def download_transcript Net::HTTP.get(URI("http://video.google.com/timedtext?lang=en&v=#{@video_id}")) end def download_transcript_to(output) File.open(output, "w").write(download_transcript) end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) puts 'cleaning up database...' Ingredient.destroy_all puts 'db clean' puts 'creating ingredients' Ingredient.create(name: "limão") Ingredient.create(name: "laranja") Ingredient.create(name: "menta") Ingredient.create(name: "canela") Ingredient.create(name: "manga") Ingredient.create(name: "água de coco") Ingredient.create(name: "uva") Ingredient.create(name: "abacaxi") Ingredient.create(name: "goiaba") Ingredient.create(name: "leite condensado") Ingredient.create(name: "hortelã") Ingredient.create(name: "cupuaçu") Ingredient.create(name: "framboesa") Ingredient.create(name: "maracujá") Ingredient.create(name: "açucar") Ingredient.create(name: "melancia") puts 'seed finished' # url = 'https://www.thecocktaildb.com/api/json/v1/1/list.php?i=list' # ingredients_serialized = open(url).read ingredients = JSON.parse(ingredients_serialized) # ingredients["drinks"].map { |i| i["strIngredient1"] }.each do |ingredient| Ingredient.create!(name: ingredient) end
class ExerciseCommentsController < ApplicationController before_action :authenticate_user! def index @exercise_comments = ExerciseComment.all end def create p params ExerciseComment.create( content: params[:content], user: current_user, exercise: Exercise.find(params[:exercise]) ) end def show @exercise_comments = ExerciseComment.find(params[:id]) end end
require "minitest/autorun" require './lib/phone_number' class PhoneNumberTest < MiniTest::Test def test_it_exists phone_number = PhoneNumber.new assert_kind_of PhoneNumber, phone_number end def test_it_is_initialized_from_a_phone_number number = '4236466119' pn = PhoneNumber.new(number) assert_equal '4236466119', pn.phone_number end def test_it_can_change_phone_numbers number = '2024556677' pn = PhoneNumber.new(number) assert_equal number, pn.phone_number pn.phone_number = "5555555555" assert_equal "5555555555", pn.phone_number end def test_it_cleans_up_phone_numbers_with_periods_and_hyphens pn = PhoneNumber.new( '202.444.9382') assert_equal '2024449382', pn.phone_number end def test_it_cleans_up_phone_numbers_with_spaces_and_parentheses pn = PhoneNumber.new('(202) 444 9382') assert_equal '2024449382', pn.phone_number end def test_it_removes_leading_one_from_an_eleven_digit_phone_number pn = PhoneNumber.new('12024449382') assert_equal '2024449382', pn.phone_number end def test_it_throws_away_numbers_that_are_too_long pn = PhoneNumber.new('23334445555') assert_equal '0000000000', pn.phone_number end def test_it_throws_away_numbers_that_are_too_long pn = PhoneNumber.new('222333444') assert_equal '0000000000', pn.phone_number end end
class PeersController < ApplicationController before_action :set_peer, only: [:show, :edit, :update, :destroy] # GET /peers # GET /peers.json def index @peers = Peer.all end # GET /peers/1 # GET /peers/1.json def show end # GET /peers/new def new @peer = Peer.new end # GET /peers/1/edit def edit end # POST /peers # POST /peers.json def create @peer = Peer.new(peer_params) respond_to do |format| if @peer.save format.html { redirect_to @peer, notice: 'Peer was successfully created.' } format.json { render :show, status: :created, location: @peer } else format.html { render :new } format.json { render json: @peer.errors, status: :unprocessable_entity } end end end # PATCH/PUT /peers/1 # PATCH/PUT /peers/1.json def update respond_to do |format| if @peer.update(peer_params) format.html { redirect_to @peer, notice: 'Peer was successfully updated.' } format.json { render :show, status: :ok, location: @peer } else format.html { render :edit } format.json { render json: @peer.errors, status: :unprocessable_entity } end end end # DELETE /peers/1 # DELETE /peers/1.json def destroy @peer.destroy respond_to do |format| format.html { redirect_to peers_url, notice: 'Peer was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_peer @peer = Peer.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def peer_params params.require(:peer).permit(:device_id, :autnum_id, :neighbor) end end
require 'rails_helper' include Rails.application.routes.url_helpers resource 'Users' do let(:raw_post) { params.to_json } let(:email) { 'sample@example.com' } let(:user_password) { 'password' } before do @user = create(:user, email: email, password: user_password) header 'Content-Type', 'application/json' header 'Accept', 'application/json' end post '/auth/sign_in' do with_options scope: :user, required: true do parameter :email, 'User email' parameter :password, 'User password' end context 'when invalid params' do example 'Unsuccessful attempt to sign in', document: false do do_request({ email: 'some_email@example.com', password: 'some_password' }) expect(json_response['errors']).to eq(["Invalid login credentials. Please try again."]) expect(response_status).to eq(401) end end context 'when valid params' do example 'Sign in' do do_request({ email: @user.email, password: @user.password }) expect(json_response['data']['email']).to eq(email) expect(response_headers['token-type']).to match(/Bearer/) expect(response_headers['access-token']).not_to be_empty expect(response_status).to eq 200 end end end post '/auth' do with_options scope: :user do parameter :email, 'User email', required: true parameter :password, 'User password', required: true parameter :password_confirmation, 'User password confirmation', required: true end context 'when invalid params' do example 'Unsuccessful attempt to register', document: false do do_request({ email: '' }) expect(response_status).to eq(422) end end context 'when valid params' do example 'Register new account' do do_request({ email: "newuser@example.com", password: user_password, password_confirmation: user_password }) expect(User.count).to eq(2) expect(json_response['data']['email']).to eq('newuser@example.com') expect(response_status).to eq 200 end end end delete '/auth/sign_out' do example 'Sign out' do do_request(@user.create_new_auth_token) expect(response_status).to eq(200) expect(response_headers['access-token']).to eq(nil) end end end
# frozen_string_literal: true module Readings # This class is used in Api:ReadingsController class Create < Mutations::Command required do float :temperature float :humidity float :battery_charge string :household_token end def execute set_reading_stats set_sum_stats set_min_max_stats set_sequence_number enqueue_readning_save sequence_number end private def set_reading_stats Rails.configuration.redis.set( household_token, inputs.slice(:temperature, :humidity, :battery_charge).to_json ) end def set_sum_stats Rails.configuration.redis.incrbyfloat("#{household_token}.temperature_sum", temperature) Rails.configuration.redis.incrbyfloat("#{household_token}.humidity_sum", humidity) Rails.configuration.redis.incrbyfloat("#{household_token}.battery_charge_sum", battery_charge) end def set_min_max_stats if Rails.configuration.redis.get("#{household_token}.temperature_min").nil? || Rails.configuration.redis.get("#{household_token}.temperature_min").to_f > temperature Rails.configuration.redis.set("#{household_token}.temperature_min", temperature) end if Rails.configuration.redis.get("#{household_token}.temperature_max").nil? || Rails.configuration.redis.get("#{household_token}.temperature_max").to_f < temperature Rails.configuration.redis.set("#{household_token}.temperature_max", temperature) end if Rails.configuration.redis.get("#{household_token}.humidity_min").nil? || Rails.configuration.redis.get("#{household_token}.humidity_min").to_f > humidity Rails.configuration.redis.set("#{household_token}.humidity_min", humidity) end if Rails.configuration.redis.get("#{household_token}.humidity_max").nil? || Rails.configuration.redis.get("#{household_token}.humidity_max").to_f < humidity Rails.configuration.redis.set("#{household_token}.humidity_max", humidity) end if Rails.configuration.redis.get("#{household_token}.battery_charge_min").nil? || Rails.configuration.redis.get("#{household_token}.battery_charge_min").to_f > battery_charge Rails.configuration.redis.set("#{household_token}.battery_charge_min", battery_charge) end if Rails.configuration.redis.get("#{household_token}.battery_charge_max").nil? || Rails.configuration.redis.get("#{household_token}.battery_charge_max").to_f < battery_charge Rails.configuration.redis.set("#{household_token}.battery_charge_max", battery_charge) end end def set_sequence_number Rails.configuration.redis.incr("#{household_token}.count") end def enqueue_readning_save SaveReadingJob.perform_later(inputs.merge(number: sequence_number)) end def sequence_number @sequence_number ||= Rails.configuration.redis.get("#{household_token}.count") end end end
class ApplicationController < ActionController::Base protect_from_forgery def is_admin unless(session[:admin]) redirect_to admin_login_path end end def is_in_blacklist(user_id, block_id) Blacklist.where(:user_id => user_id, :block_id => block_id).count > 0 end end
# frozen_string_literal: true class PageViewLog < ::ActiveRecord::Base class << self def create_yesterday_data # 早朝だとまだ昨日のデータは作成されていないため一昨日っぽくなっているがこれでOK # @type var yesterday: ::Time yesterday = ::Time.now.beginning_of_day - 2.day create_from_big_query(yesterday) end def create_from_big_query(target_date) return unless ::PageViewLog.where(target_date: target_date).empty? ::ActiveRecord::Base.transaction do ::Ggl::BigQuery.get_page_views(target_date).each do |result| page_location = result[:page_location].gsub(/\?.*/, '').gsub(%r{https?://.*?/}, '/')[..254] attrs = { page_location: page_location, count: result[:count], target_date: target_date } create!(**attrs) end end end def update_page_view_colmuns results = { artists: ::Hash.new(0), albums: ::Hash.new(0), tracks: ::Hash.new(0), playlist: ::Hash.new(0) } ::PageViewLog.all.each do |pv| results.each_key do |key| next unless (match = pv.page_location.match(%r{/#{key}/(?<id>.*)})) id = match[:id] results[key][id] += pv.count end end ::ActiveRecord::Base.transaction do results.each_key do |table_name| next unless results[table_name].present? t2 = results[table_name].map { |id, pv| "select '#{id}' as id, '#{pv}' as pv" } .join(' union all ') ::ActiveRecord::Base.connection.execute(<<~SQL) UPDATE #{table_name.to_s.pluralize} t1, ( #{t2} ) t2 SET t1.pv = t2.pv WHERE t1.id = t2.id SQL end end end end end
class CreateElevators < ActiveRecord::Migration[5.2] def change create_table :elevators do |t| t.string :serialNumber t.references :status, foreign_key: true t.date :inspectionDate t.date :installDate t.string :certificat t.text :information t.text :note t.references :type, foreign_key: true t.references :column, foreign_key: true t.references :category, foreign_key: true t.timestamps end end end
require 'spec_helper' feature 'Create Event' do let!(:host) { FactoryGirl.create :host } let!(:event) { FactoryGirl.create :event } before(:each) do web_login host end context 'on host events display page' do it 'can create event with valid input' do visit host_events_path(host) fill_in 'event_name', with: "Test Event" fill_in 'event_address', with: "717 California" expect{click_button "Create Camping Trip"}.to change{Event.all.count}.by(1) expect(page).to have_content "Congratulations" end it 'goes to the event index page is a name is not passed in to the form' do visit host_events_path(host) fill_in 'event_name', with: nil click_button "Create Camping Trip" expect(page).to have_content("Name can't be blank") end end describe 'Delete Event' do context 'on host events display page' do it 'can delete an event' do event = Event.create name: "whatever", host_id: 1, address: "Jenner Inn & Event Center, 25050 California 1, Jenner, CA" visit host_events_path(host) expect{click_link "X"}.to change{Event.all.count}.by(-1) expect(page).to_not have_content "Test Event" end end end describe 'add custom item' do context 'on single event page' do it 'can create a new item' do visit host_events_path(host) fill_in 'event_name', with: "New Event" fill_in 'event_address', with: '717 California' click_button "Create Camping Trip" click_link "Let me get started already!" fill_in 'item_name', with: "Test Item" expect{click_button "Add Item"}.to change{Item.all.count}.by(1) expect(page).to have_content "Test Item" end it 'can change the state of an item to important' do event = Event.create name: "Test Event #2", host_id: host.id, address: "717 California" item = Item.create name: "Test Item #2", event_id: event.id visit host_events_path(host) click_link "Test Event #2" expect{click_link "essential_button"}.to change{item.reload.important} end it 'can change the state of an item to I got it' do event = Event.create name: "Test Event #2", host_id: host.id, address: "717 California" item = Item.create name: "Test Item #2", event_id: event.id guest = Guest.create guest_2 = Guest.create guest_3 = Guest.create visit host_event_path(host, event) expect(page).to have_content("no") expect{click_link "purchased_button"}.to change{item.reload.purchased} end it 'can remove an item from an events page' do event = Event.create name: "Test Event #2", host_id: host.id, address: "717 California" item = Item.create name: "Test Item #2", event_id: event.id guest = Guest.create guest_2 = Guest.create guest_3 = Guest.create visit host_event_path(host, event) expect(page).to have_content("no") expect{click_link "X"}.to change{Item.all} end end describe 'add custom item' do context 'on single event page' do it 'can update the location of an event' do event = Event.create name: "Test Event #2", host_id: host.id, address: "717 California" item = Item.create name: "Test Item #2", event_id: event.id visit host_events_path(host) click_link "Test Event #2" click_link "Edit Trip" fill_in "event_address", with: "224 Evergreen Drive" expect{click_button "Update"}.to change{event.reload.address} end end end end end
class Sermon < ActiveRecord::Base has_many :notes validates :book, :s_date, :chapter, :verse_first, :verse_last, presence: true include PgSearch pg_search_scope :search, against: [:book, :outline], using: {tsearch: {dictionary: "english"}} def self.recent where(published: [true, nil]).order("s_date DESC").limit(5) end def self.ordered(params) where(published: [true, nil]).order("s_date DESC").paginate(page: params[:page]) end def self.all_sermons all.order("s_date DESC") end def self.text_search(query) if query.present? search(query) #where("to_tsvector('english', book) @@ :q or to_tsvector('english', outline) @@ :q", q: query) else scoped end end end
class SecureController < PutitController before do check_token end private def check_token authorization = request.env['HTTP_AUTHORIZATION'] unless authorization halt 401, { status: 'error', errors: 'Auth required' }.to_json end type, token = authorization.split(' ') unless type == 'Bearer' halt 401, { status: 'error', errors: 'Missing Bearer token type.' }.to_json end unless token halt 401, { status: 'error', errors: 'Missing Bearer token type.' }.to_json end if token_blocked(token) halt 401, { status: 'error', errors: 'Token was invalidated.' }.to_json end unless token_decode(token) halt 401, { status: 'error', errors: 'Unable to decode token.' }.to_json end end def token_blocked(encoded_token) BlockedToken.exists?(token: encoded_token) end def token_decode(encoded_token) options, payload = encoded_token.split('.') options = JSON.parse(Base64.decode64(options), symbolize_names: true) payload = JSON.parse(Base64.decode64(payload), symbolize_names: true) if payload[:user_type] == 'api' user = ApiUser.find_by_email(payload[:user]) elsif payload[:user_type] == 'web' user = User.find_by_email(payload[:user]) end JWT.decode encoded_token, user.secret_key, true, algorithm: options[:alg] RequestStore.store[:current_user] ||= user.email logger.info("User \"#{user.email}\" authorized.", user_type: payload[:user_type]) true rescue StandardError false end end
FactoryBot.define do factory :facility_business_identifier do sequence(:id) { |n| n } identifier { SecureRandom.uuid } identifier_type { "dhis2_org_unit_id" } facility end end
require "twitter" def getTweets(searchTerm, tweetCount) begin data = Hash.new File.readlines(File.join(File.expand_path(File.dirname(__FILE__)), "twitterToken.txt")).each do |line| var, val = line.chomp.split("=") data[var] = val end client = Twitter::REST::Client.new do |config| config.consumer_key = data["consumer_key"] config.consumer_secret = data["consumer_secret"] config.access_token = data["access_token"] config.access_token_secret = data["access_token_secret"] end twitterData = Array.new if searchTerm[0] == "@" tweets = client.user_timeline(searchTerm, count: tweetCount) else tweets = client.search(searchTerm, lang: "en").take(tweetCount) end tweets.each { |tweet| twitterData.push(tweet.full_text) } twitterData rescue => e raise StandardError.new(e.inspect.tr(">", "").tr("<", "") << "<br>" << e.backtrace.join("\n")) end end method(:getTweets)
require_relative 'base' module SPV class Fixtures module Modifiers # It takes a fixture and replaces a shortcut path with # a full path to it. class ShortcutPath < Base def modify(fixture) if shortcut = fixture.shortcut_path if path = @options.shortcut_path(shortcut) fixture.set_home_path(path) else raise ArgumentError.new( "You are trying to use the '#{shortcut}' shortcut path for #{fixture.name} fixture. " \ "This shortcut path cannot be used since it is not defined, please refer to the documentation " \ "to make sure you properly define the shortcut path." ) end end end end end end end
Rails.application.routes.draw do mount Rswag::Ui::Engine => '/api-docs' mount Rswag::Api::Engine => '/api-docs' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html namespace :api, path: "api" do namespace :v1, path: "v1" do #post "/signup", to: "users#signup" resources :users, only: [:show] do collection do post "signup" post "login" end get "cart" end resources :categories, only: [:index] do get 'products' end resources :products, only: [:index] resources :carts, only: [:show] do collection do post "add_product" end end end end end
class ApplicationMailer < ActionMailer::Base default from: 'meaghan.m.jones@gmail.com' layout 'mailer' end
class CreateMobilizations < ActiveRecord::Migration[6.0] def change create_table :mobilizations do |t| t.string :type_mobilization t.integer :participants, default: 0 t.integer :new_members_sign_ons, default: 0 t.integer :total_one_time_donations, default: 0 t.integer :xra_donation_suscriptions, default: 0 t.integer :arrestable_pledges, default: 0 t.integer :xra_newsletter_sign_ups, default: 0 t.references :chapter, null: false, foreign_key: true t.references :user, null: false, foreign_key: true t.timestamps end end end
module Rubinius class ByteArray def self.mutable_primitive_instances? true end end end
# 3 inputs form user: # 1) number1 and number2 for operation # 2) arithmatic operation def say(message) puts "=> #{message}" end # Check if input is a number, which include characters: # 1. "-" at front if exist # 2. only one "." # 3. digits def check_number(num) if num =~ /^-?\d+(\.\d+)?$/ true else puts "Error input #{num} is not a number, try again!" end end loop do say "Please input number 1: " num1 = gets.chomp next unless check_number(num1) say "Please input number 2: " num2 = gets.chomp next unless check_number(num2) say "For following operations: " say "1) add" say "2) subtract" say "3) multiply" say "4) divide" say "Choose which arithmatic to do (input in number): " operator = gets.chomp.to_i num1 = num1.to_f num2 = num2.to_f case operator when 1 result = num1 + num2 when 2 result = num1 - num2 when 3 result = num1 * num2 when 4 if num2 == 0 say "Error divide by 0, please input again" next else result = num1 / num2 end end break if operator == 5 say "Result is #{result}" say "Do another calculation? (Y/N) " continue = gets.chomp.downcase case continue when 'y' then next when 'n' then break else say "Cannot recognize input #{continue}, terminate" break end end
class AddPointsNameToLoyaltyConfigs < ActiveRecord::Migration def change add_column :loyalty_configs, :points_name, :string, default: "Stars" end end
class OrangeTree def initialize stage @stage = stage @height = 0 @age = 0 # He's full. @oranges = 0 # He doesn't need to go. end def measure_growth puts "You measure the height of your orange tree." puts "It is #{@height} feet tall." if @height < 5 puts "your tree is a sappling" @stage = "sappling" elsif @height >= 5 && @height < 10 puts "Your tree is a teenager. The juice might be a little sour and wear eye liner." @stage = "teengager" else puts "your tree is all grown up!" @stage = "adult" end season_passes end def pick_oranges if @oranges == 0 puts "There are no oranges to harvest." else puts "You harvest #{@oranges} oranges." end end private def season_passes @age = @age + 1 @height = @height + 1 @oranges = 0 if @stage == "sappling" @oranges = 0 elsif @stage == "teengager" @oranges = (@age + 1) * @height end if @stage == "adult" @oranges = (@age + 1) * @height end end end my_tree = OrangeTree.new("sappling") puts my_tree.measure_growth puts my_tree.measure_growth puts my_tree.pick_oranges puts my_tree.measure_growth puts my_tree.measure_growth puts my_tree.measure_growth puts my_tree.pick_oranges puts my_tree.measure_growth
#!/usr/bin/env ruby ### # # This file is part of nTodo # # Copyright (c) 2009 Wael Nasreddine <wael.nasreddine@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, # USA. # ### # Put the library folder in the load path $:.unshift File.join(File.dirname(__FILE__), *%w[.. lib]) # Require the optparse to parse options given to the command line require 'optparse' # Require todo which bootstraps the todo require 'ntodo' # Set the help topic help = <<HELP ntodo is a powerfull ncurses-based todo, you can add tasks, start working on them, pause it, stop it and send the recap mail to the defined users in the configuration files Configuration is read from ~/.config/ntodo/config.yml HELP # Cycle throught the opts and set the options options = {} opts = OptionParser.new do |opts| opts.banner = help opts.separator "" opts.separator "Main options:" opts.on("-a", "--add", "Add a new project/task (require -p or -t)") do begin options[:operation] = {} if options[:operation].nil? if options[:operation][:type] raise ArgumentError else options[:operation][:type] = :add end rescue puts "Sorry, but you cannot request more than one operation at a time." exit 1 end end opts.on("-d", "--delete", "Delete a project/task (require -p or -t)") do begin options[:operation] = {} if options[:operation].nil? if options[:operation][:type] raise ArgumentError else options[:operation][:type] = :delete end rescue puts "Sorry, but you cannot request more than one operation at a time." exit 1 end end opts.on("-l", "--list", "List project/task (if -p given tasks will be listed, projects otherwize)") do begin options[:operation] = {} if options[:operation].nil? if options[:operation][:type] raise ArgumentError else options[:operation][:type] = :list end rescue puts "Sorry, but you cannot request more than one operation at a time." exit 1 end end opts.separator "" opts.separator "Secondary options:" opts.on("-p", "--project Project", "Operate on a project") do |name| options[:operation] = {} if options[:operation].nil? options[:operation][:project] = name end opts.on("-t", "--task Title", "Operate on a task") do |name| options[:operation] = {} if options[:operation].nil? options[:operation][:task] = {} if options[:operation][:task].nil? options[:operation][:task][:title] = name end opts.on("-D", "--description Desctiption", "Add the description of the task from the command-line") do |description| begin raise ArgumentError if options[:operation].nil? || options[:operation][:type].nil? || options[:operation][:task].nil? options[:operation][:task][:description] = description rescue puts "Before invoking -D, you should pass -a and -t options" exit 1 end end opts.separator "" opts.separator "Common options:" opts.on_tail("-h", "--help", "Show this message") do puts opts exit end opts.on("--debug", "Display debugging message") do options[:debug] = true end opts.on("--version", "Display current version") do puts "nTodo " + Ntodo.version exit end end module Ntodo class Main def initialize(options, opts) @options = options @opts = opts end def execute # Read command line options @opts.parse! # Begin bootstrap begin app = Ntodo::Bootstrap.new(@options) rescue => err puts "#{err.message} (#{err.class})" err.backtrace.each { |frame| puts frame } end # Run begin app.execute rescue => err puts "#{err.message} (#{err.class})" err.backtrace.each { |frame| puts frame } end end end end if $0 == __FILE__ main = Ntodo::Main.new(options, opts) main.execute end
Then /^homepage is displayed$/ do URI.parse(current_url).path.should == root_path end Then /^profile is displayed$/ do URI.parse(current_url).path.should == user_path(@user) end Then /^repeate activation page is displayed$/ do URI.parse(current_url).path.should == repeate_activation_user_path(@user) end
require_relative 'test_helper' class InvoiceRepositoryTest < Minitest::Test attr_reader :invoice_repository, :sales_engine, :data def setup @data = "test/fixtures/invoices_fixtures.csv" @invoice_repository = InvoiceRepository.new('test/fixtures/invoices_fixtures.csv', self) @sales_engine = Minitest::Mock.new end def test_it_exists assert invoice_repository end def test_the_fixture_file_to_read_exists assert File.exist?(invoice_repository.file) end def test_it_creates_all_invoices assert 10, invoice_repository.all.count end def test_it_returns_a_random_instance test = [] 100.times { test << invoice_repository.random } test = test.uniq assert test.count > 1 end def test_it_returns_a_find_by_id_match assert_equal "1", invoice_repository.find_by_id("1").id end def test_it_returns_a_find_by_customer_id_match assert_equal "1", invoice_repository.find_by_customer_id("1").customer_id end def test_it_returns_a_find_by_merchant_id_match assert_equal "26", invoice_repository.find_by_merchant_id("26").merchant_id end def test_it_returns_a_find_by_status_match assert_equal "shipped", invoice_repository.find_by_status("shipped").status end def test_it_returns_a_find_all_by_customer_id_match assert_equal 8, invoice_repository.find_all_by_customer_id("1").count end def test_it_returns_a_find_all_by_merchant_id_match assert_equal 2, invoice_repository.find_all_by_merchant_id("26").count end def test_it_returns_a_find_all_by_status_match assert_equal 10, invoice_repository.find_all_by_status("shipped").count end def test_method_calls_sales_engine invoice_repository = InvoiceRepository.new(data, sales_engine) sales_engine.expect(:find_items_by_invoice_id, nil, [1]) invoice_repository.find_items_by_invoice_id(1) sales_engine.verify end end
require 'spec_helper' describe DummySonsController, type: :controller do describe '#index' do let!(:model_count) { 28 } let!(:dummy_models) { create_list(:dummy_model, model_count, :with_son) } let(:expected_list) do dummy_models.first(25).map do |dummy| dummy_son = dummy.dummy_model_sons.first dummy_grand_son = dummy.dummy_model_sons.first.dummy_model_grand_sons.first { 'id' => dummy.id, 'name' => dummy.name, 'something' => dummy.something, 'dummy_model_sons' => [ 'id' => dummy_son.id, 'name' => dummy_son.name, 'something' => dummy_son.something, 'dummy_model_grand_sons' => [ 'id' => dummy_grand_son.id, 'name' => dummy_grand_son.name, 'something' => dummy_grand_son.something ] ] } end end context 'when paginating an ActiveRecord with no previous pagination but kaminari installed' do before { get :index } include_context 'with default pagination params' include_examples 'proper pagination params' include_examples 'valid page' end context 'when paginating with page and limit params' do context 'with a particular limit passed by option' do let(:expected_list) do dummy = dummy_models.third dummy_son = dummy.dummy_model_sons.first dummy_grand_son = dummy.dummy_model_sons.first.dummy_model_grand_sons.first [{ 'id' => dummy.id, 'name' => dummy.name, 'something' => dummy.something, 'dummy_model_sons' => [ 'id' => dummy_son.id, 'name' => dummy_son.name, 'something' => dummy_son.something, 'dummy_model_grand_sons' => [ 'id' => dummy_grand_son.id, 'name' => dummy_grand_son.name, 'something' => dummy_grand_son.something ] ] }] end let(:pagination_params) do { page: Wor::Paginate::Config.default_page, count: Wor::Paginate::Config.default_page, total_count: model_count, total_pages: model_count, previous_page: 2, current_page: 3, next_page: 4 } end before { get :index_with_params } include_examples 'proper pagination params' include_examples 'valid page' end context 'with a really high limit passed by option' do let(:expected_list) do dummy_models.first(50).map do |dummy| dummy_son = dummy.dummy_model_sons.first dummy_grand_son = dummy.dummy_model_sons.first.dummy_model_grand_sons.first { 'id' => dummy.id, 'name' => dummy.name, 'something' => dummy.something, 'dummy_model_sons' => [ 'id' => dummy_son.id, 'name' => dummy_son.name, 'something' => dummy_son.something, 'dummy_model_grand_sons' => [ 'id' => dummy_grand_son.id, 'name' => dummy_grand_son.name, 'something' => dummy_grand_son.something ] ] } end end let!(:model_count) { 150 } let(:pagination_params) do { page: 50, count: 50, total_count: model_count, total_pages: 3, previous_page: nil, current_page: Wor::Paginate::Config.default_page, next_page: 2 } end before { get :index_with_high_limit } include_examples 'proper pagination params' include_examples 'valid page' end end context 'when paginating an ActiveRecord with a scope' do # Requiring both kaminari and will_paginate breaks scope pagination before { get :index_scoped } include_context 'with default pagination params' include_examples 'proper pagination params' include_examples 'valid page' end context 'when paginating an ActiveRecord paginated with kaminari' do before { get :index_kaminari } include_context 'with default pagination params' include_examples 'proper pagination params' include_examples 'valid page' end context 'when paginating an ActiveRecord paginated with will_paginate' do before { get :index_will_paginate } include_context 'with default pagination params' include_examples 'proper pagination params' include_examples 'valid page' end context 'when paginating an array' do before { get :index_array } include_context 'with default pagination params' include_examples 'proper pagination params' it 'responds with valid page' do expect(response_body(response)['page']).to eq((1..25).to_a) end end context 'when paginating arrays with param page in -1' do it 'throws exception' do expect { get :index_array, params: { page: -1 } } .to raise_exception(Wor::Paginate::Exceptions::InvalidPageNumber) end end context 'when paginating arrays with per page in -1' do it 'throws exception' do expect { get :index_array, params: { per: -1 } } .to raise_exception(Wor::Paginate::Exceptions::InvalidLimitNumber) end end context 'when paginating something that can\'t be paginated' do it 'throws an exception' do expect { get :index_exception } .to raise_error(Wor::Paginate::Exceptions::NoPaginationAdapter) end end context 'when paginating an ActiveRecord with a custom serializer' do before { get :index_each_serializer } include_context 'with default pagination params' include_examples 'proper pagination params' include_examples 'valid page' end context 'when paginating an ActiveRecord with a custom formatter' do before { get :index_custom_formatter } it 'doesn\'t respond with page in the default key' do expect(response_body(response)['page']).to be_nil end it 'responds with valid page' do expect(response_body(response)['items']).to eq expected_list end end end end
require 'json' require 'mongo' require 'runners/unified' Mongo::Logger.logger.level = Logger::WARN class UnknownOperation < StandardError; end class UnknownOperationConfiguration < StandardError; end class Executor def initialize(uri, spec) @uri, @spec = uri, spec @iteration_count = @success_count = @failure_count = @error_count = 0 @exceptions = [] end attr_reader :uri, :spec attr_reader :iteration_count, :failure_count, :error_count def run unified_tests set_signal_handler begin unified_tests.each do |test| test.create_spec_entities test.set_initial_data @test_running = true begin test.run ensure @test_running = false end test.assert_outcome test.assert_events test.cleanup end rescue => exc @exceptions << { error: "#{exc.class}: #{exc}", time: Time.now.to_f, } STDERR.puts "Error: Uncaught exception: #{exc.class}: #{exc}." STDERR.puts "Waiting for termination signal to exit" @test_running = true until @stop sleep 1 end @test_running = false end write_result puts "Result: #{result.inspect}" end private def set_signal_handler Signal.trap('INT') do if @test_running # Try to gracefully stop the looping. @stop = true unified_tests.each do |test| test.stop! end Thread.new do # Default server selection timeout is 30 seconds. sleep 45 STDERR.puts "Warning: Exiting from signal handler background thread because executor did not terminate in 45 seconds" exit(1) end else # We aren't looping, exit immediately otherwise runner gets stuck. raise end end end def unified_group @unified_group ||= Unified::TestGroup.new(spec, client_args: uri) end def unified_tests @tests ||= unified_group.tests end def result { numIterations: @iteration_count, numSuccessfulOperations: @success_count, numSuccesses: @success_count, numErrors: @error_count, numFailures: @failure_count, } end def write_result {}.tap do |event_result| @iteration_count = -1 @success_count = -1 @events = [] @errors = [] @failures = [] unified_tests.map do |test| begin @iteration_count += test.entities.get(:iteration_count, 'iterations') rescue Unified::Error::EntityMissing end begin @success_count += test.entities.get(:success_count, 'successes') rescue Unified::Error::EntityMissing end begin @events += test.entities.get(:event_list, 'events') rescue Unified::Error::EntityMissing end begin @errors += test.entities.get(:error_list, 'errors') rescue Unified::Error::EntityMissing end @errors += @exceptions begin @failures += test.entities.get(:failure_list, 'failures') rescue Unified::Error::EntityMissing end end @error_count += @errors.length @failure_count += @failures.length File.open('events.json', 'w') do |f| f << JSON.dump( errors: @errors, failures: @failures, events: @events, ) end end File.open('results.json', 'w') do |f| f << JSON.dump(result) end end end
class CreateRestaurantCuisines < ActiveRecord::Migration def change create_table :restaurant_cuisines do |t| t.integer :restaurant_id t.integer :cuisine_id t.boolean :archived, default: false t.timestamps end add_index :restaurant_cuisines, :restaurant_id add_index :restaurant_cuisines, :cuisine_id add_index :restaurant_cuisines, :archived end end
require_relative 'web_helpers' feature 'Signing in' do scenario 'Users can sign in' do sign_up visit '/session/new' expect(page).to have_content('Please sign in') fill_in('email', with: 'acav@gmail.com') fill_in('password', with: 'password') click_button('Sign me in!') expect(current_path).to eq '/peeps' expect(page).to have_content('Welcome, acav') end scenario 'Wrong credentials lead to flash notif' do sign_up visit '/session/new' expect(page).to have_content('Please sign in') fill_in('email', with: 'acav@gnail.com') fill_in('password', with: 'password') click_button('Sign me in!') expect(current_path).to eq '/session/new' expect(page).to have_content('Incorrect credentials') end end
require 'test_helper' module Import class FacebookEventsImportTest < ActiveSupport::TestCase test 'check element for coordinates in area coordinates' do element = { place: { location: { latitude: '0', longitude: '0' } } }.deep_stringify_keys Translatable::AREAS.each do |area| assert_equal false, FacebookEventsImport.element_in_area?(element: element, area: area) end end test 'import complete list' do skip 'Do we need this anymore? This is not in use...' config = { dresden: { orga0815: 'fb_id_0815' } }.deep_stringify_keys Settings.facebook.stubs(:pages_for_events).returns(config) # TODO: add a real response here: response = [ { place: { location: { latitude: '0', longitude: '0' } } } ] FacebookClient.expects(:new).returns(@client = mock()) @client.expects(:raw_get_upcoming_events).with do |options| assert_equal config['dresden'].keys.first, options[:page] assert_equal config['dresden'].values.first, options[:page_id] true end.returns(response) assert_difference -> { Event.by_area('dresden').count } do assert_equal 1, FacebookEventsImport.import end end end end
class Evil::Client::Middleware class StringifyForm < Base private def build(env) return env unless env[:format] == "form" return env if env&.fetch(:body, nil).to_h.empty? env.dup.tap do |hash| hash[:headers] ||= {} hash[:headers]["content-type"] = "application/x-www-form-urlencoded" hash[:body_string] = env[:body] .flat_map { |key, val| normalize(val, key) } .flat_map { |item| stringify(item) } .join("&") end end def stringify(hash) hash.map do |keys, val| "#{keys.first}#{keys[1..-1].map { |key| "[#{key}]" }.join}=#{val}" end end def normalize(value, *keys) case value when Hash then value.flat_map { |key, val| normalize(val, *keys, key) } when Array then value.flat_map { |val| normalize(val, *keys, nil) } else [{ keys.map { |key| CGI.escape(key.to_s) } => CGI.escape(value.to_s) }] end end end end
class CreateImages < ActiveRecord::Migration def change create_table :images do |t| t.references :entry t.timestamps end add_index :images, :entry_id add_attachment :images, :photo end end
require "rails_helper" feature "Destroy course" do subject {page} let(:supervisor) {FactoryGirl.create :supervisor} let!(:course){FactoryGirl.create :course, user_ids: [supervisor.id]} before :each do course.finished! login_as supervisor, scope: :user visit supervisor_courses_path end scenario "has delete button" do Course.finished.each do |course| is_expected.to have_link(I18n.t("supervisor.courses.course.delete"), href: "/supervisor/courses/#{course.id}") end end scenario "destroy course feature", js: true do click_link(I18n.t("supervisor.courses.course.delete"), href: "/supervisor/courses/#{course.id}") sleep 3 page.driver.browser.switch_to.alert.accept is_expected.to have_text I18n.t "supervisor.courses.destroy.course_delete" end end
# frozen_string_literal: true module Types module Objects class ArtistObject < ::Types::Objects::BaseObject description 'アーティスト' field :id, ::String, null: false, description: 'ID' field :name, ::String, null: false, description: '名前' field :status, ::Types::Enums::StatusEnum, null: false, description: 'ステータス' field :release_date, ::GraphQL::Types::ISO8601DateTime, null: false, description: '発売日' field :created_at, ::GraphQL::Types::ISO8601DateTime, null: false, description: '追加日' field :artwork_l, ::Types::Objects::ArtworkObject, null: false, description: '大型アートワーク' field :artwork_m, ::Types::Objects::ArtworkObject, null: false, description: '中型アートワーク' end end end
=begin You don't trust your users. Modify the program below to require the user to enter the same value twice in order to add that value to the total. Example run: Hello! We are going to total some numbers! Enter a negative number to quit. 3 3 2 2 -1 -1 Result: 5 =end puts "Hello! We are going to total some numbers!" puts "Enter a negative number to quit." total = 0 input = 0 input2 = 0 while input > -1 && input2 > -1 puts "Enter your number: " input = gets.chomp.to_i puts "Enter your number again: " input2 = gets.chomp.to_i while input2 != input puts "Your numbers do not match. Please re-enter:" input2 = gets.chomp.to_i end if input2 >= 0 total += input2 end end #puts "Enter your number again: " #input = gets.chomp.to_i puts "Result: #{total}"
class SecretsController < ApplicationController before_action :require_login, only: [:new, :create, :destroy] def new @secrets = Secret.all end def create Secret.create(content: params[:content], user_id: params[:id]) redirect_to :back end def destroy secret = Secret.find(params[:id]) secret.destroy if secret.user == current_user redirect_to "/users/#{current_user.id}" end private def secret_params params.require(:secret).permit(:content) end end
class Company < ActiveRecord::Base has_many :company_reviews has_many :products validates :name, :catch_phrase, :suffix, presence: true end
class Admin::ZhangmenjueController < ApplicationController layout 'admin' before_filter :validate_login_admin def index user = User.find(session[:user_id]) #用户的掌门诀 @zhangmenjues = user.zhangmenjues.paginate(:page => params[:page]) #将用户的掌门诀以字典形式存储 @zhangmenjues_info = {} @zhangmenjues.each() do |zhangmenjue| @zhangmenjues_info[zhangmenjue.id] = zhangmenjue.get_zhangmenjue_details end end def show @zhangmenjue = Zhangmenjue.find(params[:id]) #将用户的掌门诀以字典形式存储 @zhangmenjues_info = {} @zhangmenjues_info[@zhangmenjue.id] = @zhangmenjue.get_zhangmenjue_details end def edit @zhangmenjue = Zhangmenjue.find(params[:id]) #将掌门诀以字典形式存储 @zhangmenjues_info = {} @zhangmenjues_info[@zhangmenjue.id] = @zhangmenjue.get_zhangmenjue_details end def update @zhangmenjue = Zhangmenjue.find(params[:id]) #将用户的掌门诀以字典形式存储 @zhangmenjues_info = {} @zhangmenjues_info[@zhangmenjue.id] = @zhangmenjue.get_zhangmenjue_details level = params[:zhangmenjue][:level] poli = params[:zhangmenjue][:poli] score = params[:zhangmenjue][:score] re = @zhangmenjue.update_attributes(level: level, poli: poli, score: score) respond_to do |format| if re format.html{ redirect_to :action => :show, :id => @zhangmenjue.id} else format.html{ render :action => :edit} end end end def delete zhangmenjue = Zhangmenjue.find_by_id(params[:id]) zhangmenjue.destroy unless zhangmenjue.nil? redirect_to(action: :index) end def new #@zhangmenjue = Zhangmenjue.new end def create #user_id = session[:user_id] #z_type = params[:zhangmenjue][:z_type] #level = params[:zhangmenjue][:level] #poli = params[:zhangmenjue][:poli] #score = params[:zhangmenjue][:score] #@zhangmenjue = Zhangmenjue.new(z_type: z_type, level: level, poli: poli, score: score, user_id: user_id) #respond_to do |format| # if @zhangmenjue.save # format.html { redirect_to(:action => :show, :id => @zhangmenjue.id) } # else # format.html { render :action => "new" } # end #end end end
require 'spec_helper' require 'machine' require 'pry' RSpec.describe Machine, machine: true do let(:product_name) { "coke 500ml" } before(:each) do subject { described_class.new } subject.stub(:puts).with(anything()) # subject.stub(:p).with(anything()) end it 'Request user to load products' do expect(subject).to receive(:puts).with("Enter a quantity of coke 500ml to load") allow(subject).to receive(:gets).and_return("1") subject.take_stock products = subject.products products.product_list do |product| expect(products.stocked_products[product][:quantity]).to eq 1 end end it 'Request user to load coins' do expect(subject).to receive(:puts).with("Enter a quantity of £2 to load") allow(subject).to receive(:gets).and_return("2") subject.take_coins coins = subject.coins coins.denominations do |denominations| expect(coins.coins[denominations][:quantity]).to eq 2 end end it 'Request user to make a selection' do expect(subject).to receive(:puts).with("Please type in the name of your selection") expect(subject).to receive(:puts).with("coke 500ml : £1.25") allow(subject).to receive(:gets).and_return("coke 500ml") subject.select_product end it 'Request user to enter change' do msg = "Enter a coin and press enter. When finished, hit enter twice" expect(subject).to receive(:puts).with(msg) allow(subject).to receive(:gets).and_return("50p", "") subject.get_user_payment end it 'checks the value of the change is enough to buy the product' do subject.user_payment.push('50p', '50p') subject.user_selection << "coke 500ml" expect(subject.payment_sufficient?).to be false end end
class PostsController < ApplicationController load_and_authorize_resource # GET /posts # GET /posts.json def index @d1 = params[:d1].nil? ? (Time.now - 3600*24*7).strftime("%F") : params[:d1] @d2 = params[:d2].nil? ? Time.now.strftime("%F") : params[:d2] @posts = Post.where("DATE(created_at) >= ? AND DATE(created_at) <= ?",@d1,@d2).search(params[:search]).order(sort_column + " " + sort_direction).paginate(:per_page => COUNT_STRING_ON_PAGE, :page => params[:page]) respond_to do |format| format.html # index.html.erb format.json { render json: @posts } end end # GET /posts/1 # GET /posts/1.json def show @post = Post.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @post } end end # GET /posts/new # GET /posts/new.json def new @post = Post.new @post.task_id = params[:task_id] respond_to do |format| format.html # new.html.erb format.json { render json: @post } end end # GET /posts/1/edit def edit @post = Post.find(params[:id]) end # POST /posts # POST /posts.json def create @post = Post.new(params[:post]) @post.staff_id = current_staff.id @post.staff_name = current_staff.lname + " " + current_staff.fname @post.wobj_name = @post.workobject.name @post.chif_name = @post.chif.lname + " " + @post.chif.fname respond_to do |format| if @post.save format.html { redirect_to params[:ref], notice: 'Post was successfully created.' } format.json { render json: params[:ref], status: :created, location: @post } else format.html { render action: "new" } format.json { render json: @post.errors, status: :unprocessable_entity } end end end # PUT /posts/1 # PUT /posts/1.json def update @post = Post.find(params[:id]) @post.staff_id = current_staff.id respond_to do |format| if @post.update_attributes(params[:post]) format.html { redirect_to @post, notice: 'Post was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @post.errors, status: :unprocessable_entity } end end end # DELETE /posts/1 # DELETE /posts/1.json def destroy @post = Post.find(params[:id]) @post.destroy respond_to do |format| format.html { redirect_to posts_url } format.json { head :no_content } end end end
module WorksheetsHelper def display_problem_number(worksheet_problem) "#{worksheet_problem.problem_number})" end def problem_links_if_editable(worksheet_problem, editable) if editable render :partial => "worksheet_problems/worksheet_problem_links", :locals => { :worksheet_problem => worksheet_problem } end end def problem_group_instructions(problem_group) problem_numbers = problem_group.map { |prob| prob.problem_number } first_word = problem_numbers.size == 1 ? 'Problem' : 'Problems' if is_range? problem_numbers numbers_list = range_string problem_numbers else numbers_list = problem_numbers.join(", ").chomp(', ') end "#{first_word} ##{numbers_list.chomp}: #{problem_group.first.instruction_description}" end def is_range?(number_list) (number_list.first .. number_list.last).to_a == number_list && number_list.size > 1 end def range_string(number_list) "#{number_list.first} - #{number_list.last}" end end
class J1900c attr_reader :options, :name, :field_type, :node def initialize @name = "Number of falls since admission/entry or reentry or prior assessment resulting in major injury (J1900c)" @field_type = RADIO @node = "J1900C" @options = [] @options << FieldOption.new("^", "NA") @options << FieldOption.new("0", "None") @options << FieldOption.new("1", "One") @options << FieldOption.new("2", "Two or more") end def set_values_for_type(klass) return "0" end end
class ForecastFacade attr_reader :id, :current_weather, :hourly_weather, :daily_weather def initialize(location) @id = 1 @location = location @current_weather = current_data @hourly_weather = hourly_data @daily_weather = daily_data end def lat_long Geocoding.new(@location).latitude_longitude end def weather_data @weather_data ||= Weather.new(lat_long).current_weather end def current_data CurrentWeather.new(weather_data[:currently]) end def hourly_data weather_data[:hourly][:data].take(24).map do |data| HourlyWeather.new(data) end end def daily_data weather_data[:daily][:data].take(7).map do |data| DailyWeather.new(data) end end end
Rails.application.routes.draw do root 'static_pages#index' get 'about' => 'static_pages#about' devise_for :users, :controllers => {registrations: 'registrations'} resources :users, only: [:show, :index] do resources :debts, except: [:index, :show] end put '/complete', to: 'debts#complete', as: :complete end
class Admin::Api::BuyerApplicationReferrerFiltersController < Admin::Api::BuyersBaseController ##~ sapi = source2swagger.namespace("Account Management API") ##~ e = sapi.apis.add ##~ e.path = "/admin/api/accounts/{account_id}/applications/{application_id}/referrer_filters.xml" ##~ e.responseClass = "application" # ##~ op = e.operations.add ##~ op.httpMethod = "GET" ##~ op.summary = "Application Referrer Filter List" ##~ op.description = "Lists referrer filters of the application." ##~ op.group = "application" # ##~ op.parameters.add @parameter_access_token ##~ op.parameters.add @parameter_account_id_by_id_name ##~ op.parameters.add @parameter_application_id_by_id_name # def index respond_with(referrer_filters, representer: ReferrerFiltersRepresenter) end ##~ op = e.operations.add ##~ op.httpMethod = "POST" ##~ op.summary = "Application Referrer Filter Create" ##~ op.description = "Adds a referrer filter to an application. Referrer filters limit API requests by domain or IP ranges." ##~ op.group = "application" # ##~ op.parameters.add @parameter_access_token ##~ op.parameters.add @parameter_account_id_by_id_name ##~ op.parameters.add @parameter_application_id_by_id_name ##~ op.parameters.add :name => "referrer_filter", :description => "Referrer filter to be created.", :dataType => "string", :required => true, :paramType => "query" # def create referrer_filter = referrer_filters.add(params[:referrer_filter]) respond_with(referrer_filter, serialize: application) end # swagger ##~ e = sapi.apis.add ##~ e.path = "/admin/api/accounts/{account_id}/applications/{application_id}/referrer_filters/{id}.xml" ##~ e.responseClass = "application" # ##~ op = e.operations.add ##~ op.httpMethod = "DELETE" ##~ op.summary = "Application Referrer Filter Delete" ##~ op.description = "Deletes a referrer filter of an application. Referrer filters limit API requests by domain or IP ranges." ##~ op.group = "application" # ##~ op.parameters.add @parameter_access_token ##~ op.parameters.add @parameter_account_id_by_id_name ##~ op.parameters.add @parameter_application_id_by_id_name ##~ op.parameters.add :name => "id", :description => "ID of referrer filter to be deleted.", :dataType => "int", :required => true, :paramType => "path" # def destroy referrer_filter.destroy respond_with(referrer_filter, serialize: application) end protected def application @application ||= accessible_bought_cinstances.find(params[:application_id]) end def referrer_filters @referrer_filters ||= application.referrer_filters end def referrer_filter @referrer_filter ||= referrer_filters.find(params[:id]) end end
require File.dirname(__FILE__) + '/../test_helper.rb' class TestAssociationRulesAndParsingApriori < Test::Unit::TestCase include Apriori def setup end def test_reading_from_a_file input = File.join(FIXTURES_DIR + "/market_basket_results_test.txt") assert rules = AssociationRule.from_file(input) assert_equal 5, rules.size assert is = AssociationRule.parse_line("apple <- doritos (50.0/3, 33.3)") assert rules.include?(is) assert is = AssociationRule.parse_line("foo <- bar baz bangle (66.7/4, 75.0)") assert rules.include?(is) end def test_parsing_individual_lines assert is = AssociationRule.parse_line("doritos <- beer (33.3/2, 100.0)") wanted = { :consequent => "doritos", :antecedent => ["beer"], :support => 33.3, :num_antecedent_transactions => 2, :confidence => 100.0, } wanted.each do |key,value| assert_equal value, is.send(key), "Expected itemset '#{key}' to be '#{value}'" end assert_equal "doritos <- beer (33.3/2, 100.0)", is.to_s assert is = AssociationRule.parse_line("apple <- doritos (50.0/3, 33.3)") wanted = { :consequent => "apple", :antecedent => ["doritos"], :support => 50.0, :num_antecedent_transactions => 3, :confidence => 33.3, } wanted.each do |key,value| assert_equal value, is.send(key), "Expected itemset '#{key}' to be '#{value}'" end assert_equal "apple <- doritos (50.0/3, 33.3)", is.to_s assert is = AssociationRule.parse_line("foo <- bar baz (66.7, 75.0)") wanted = { :consequent => "foo", :antecedent => ["bar", "baz"], :support => 66.7, :num_antecedent_transactions => nil, :confidence => 75.0, } wanted.each do |key,value| assert_equal value, is.send(key), "Expected itemset '#{key}' to be '#{value}'" end assert_equal "foo <- bar baz (66.7, 75.0)", is.to_s # foo <- bar baz bangle (66.7/4, 75.0) assert is = AssociationRule.parse_line("foo <- bar baz bangle (66.7/4, 75.0)") wanted = { :consequent => "foo", :antecedent => ["bar", "baz", "bangle"], :support => 66.7, :num_antecedent_transactions => 4, :confidence => 75.0, } wanted.each do |key,value| assert_equal value, is.send(key), "Expected itemset '#{key}' to be '#{value}'" end assert_equal "foo <- bar baz bangle (66.7/4, 75.0)", is.to_s end def test_association_rule_equality assert is = AssociationRule.parse_line("doritos <- beer (33.3/2, 100.0)") assert is2 = AssociationRule.parse_line("doritos <- beer (33.3/2, 100.0)") assert_equal is, is2 end end
require 'test_helper' class ConditionsControllerTest < ActionController::TestCase setup do @city = cities(:montevideo) end test "should get show" do get :show, city_id: @city assert_response :success assert_equal @city, assigns(:condition).city end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) Vent.destroy_all Response.destroy_all Tag.destroy_all Tagging.destroy_all vent1 = Vent.create(name: "Jordan Ballard", body: "This is my first vent and I'm stoked to be here", mood: "good", allow_response: true) vent2 = Vent.create(name: "David Ballard", body: "I just won $50,000, suckas!!!!", mood: "good", allow_response: true) vent3 = Vent.create(name: "Cliff Morris", body: "I was about to tag an elk and it bolted and I missed my opportunity...", mood: "bad", allow_response: true) Response.create(name: "Matt Vaden", body: "Welcome to The Vent!", vent_id: vent1.id) Response.create(name: "Pam Ballard", body: "Let's go on a cruise!", vent_id: vent2.id) Response.create(name: "PETA", body: "Good, you shouldn't be shooting at animals anyway!", vent_id: vent3.id) tag1 = Tag.create(name: "Happy") tag2 = Tag.create(name: "Sad") tag3 = Tag.create(name: "Angry") Tagging.create(tag_id: tag1.id, vent_id: vent1.id) Tagging.create(tag_id: tag2.id, vent_id: vent2.id) Tagging.create(tag_id: tag3.id, vent_id: vent3.id) Tagging.create(tag_id: tag2.id, vent_id: vent1.id)
class CreateLayouts < ActiveRecord::Migration def self.up create_table :layouts, :force => true do |t| t.string :title t.text :content t.integer :pages_count, :default => 0 end end def self.down drop_table :layouts end end
require 'rails_helper' RSpec.describe Highlight, type: :model do it { should belong_to :image } it { should belong_to :key } it { should belong_to :locale } it { should belong_to :location } it { should have_one :project } end
module API module V1 class CartsController < ApplicationController before_action :authenticate # Authenticate with token def show info = $redis.hgetall current_user_cart @cart = Cart.new info.each do |product_id, quantity| @cart.add_item(CartItem.new(product_id, quantity)) end render json: @cart end def add product_id = params[:product_id].to_i quantity = params[:quantity].to_i $redis.hset current_user_cart, product_id, quantity render json: current_user.cart_count, status: 200 end def remove product_id = params[:product_id].to_i $redis.hdel current_user_cart, product_id render json: current_user.cart_count, status: 200 end private def current_user_cart "cart#{current_user.id}" end protected def authenticate authenticate_token || render_unauthorized end def authenticate_token authenticate_with_http_token do |token, options| sign_in User.find_by(auth_token: token) end end def render_unauthorized self.headers['WWW-Authenticate'] = 'Token realm="Application"' render json: 'Wrong authorisation token', status: 401 end end end end
class ReferencesController < ApplicationController load_and_authorize_resource # GET /works/:work_id/references # GET /creators/:creator_id/references def index @references = Reference.all render json: @references end # GET /references/1 def show render json: @reference end # POST /works/:work_id/references # POST /creators/:creator_id/references def create @reference = Reference.new(reference_params) if @reference.save render json: @reference, status: :created, location: @reference else render json: @reference.errors, status: :unprocessable_entity end end # PATCH/PUT /references/1 def update if @reference.update(reference_params) render json: @reference else render json: @reference.errors, status: :unprocessable_entity end end # DELETE /references/1 def destroy @reference.destroy end private def reference_params params.require(:reference).permit(:note) end end
json.array!(@test_cases) do |test_case| json.extract! test_case, :id, :title, :summary, :manual_process, :automated_test_path json.url test_case_url(test_case, format: :json) end
require "./lib/human_player" describe "HumanPlayer" do it "should set the human player's mark to 'X'" do human = HumanPlayer.new("human") human.mark.should == "X" end it "should set the human player's mark to 'O'" do human = HumanPlayer.new("computer") human.mark.should == "O" end end
module Chocobo class Screen < Choco def self.size { width: MG::Director.shared.size.width, height: MG::Director.shared.size.height } end end end
class TrainerLeadInterviewsController < ApplicationController def index @trainer_lead_interviews = TrainerLeadInterview.all render json: @trainer_lead_interviews end def show @trainer_lead_interview = TrainerLeadInterview.find(params[:id]) render json: @trainer_lead_interview end def create if !params[:trainer_lead_id] @trainer_lead = TrainerLead.where(:first_name=>trainer_lead_interview_params[:first_name], :last_name=>trainer_lead_interview_params[:last_name], :email_address=>trainer_lead_interview_params[:email_address]).first_or_create do |trainer_lead| trainer_lead.first_name = trainer_lead_interview_params[:first_name] trainer_lead.last_name = trainer_lead_interview_params[:last_name] trainer_lead.email_address = trainer_lead_interview_params[:email_address] trainer_lead.phone_number = trainer_lead_interview_params[:phone_number] trainer_lead.licensed = trainer_lead_interview_params[:licensed] trainer_lead.trainer_id = trainer_lead_interview_params[:trainer_id] end end @title = "#{@trainer_lead.first_name} #{@trainer_lead.last_name} Bohemia Interview" # @trainer_lead_interview = TrainerLeadInterview.where(title: @title, trainer_id: @first_free_trainer.id, date: trainer_lead_interview_params[:date], location: "Bohemia Realty Group, 2101 Frederick Douglass Boulevard, New York, NY 10026", trainer_lead_id: @trainer_lead.id) @trainer_lead_interview = TrainerLeadInterview.where(:trainer_lead_id=>@trainer_lead.id).first_or_create do |trainer_lead_interview| trainer_lead_interview.trainer_id = trainer_lead_interview_params[:trainer_id] trainer_lead_interview.title = @title trainer_lead_interview.date = trainer_lead_interview_params[:date] trainer_lead_interview.location = "Bohemia Realty Group, 2101 Frederick Douglass Boulevard, New York, NY 10026" trainer_lead_interview.trainer_lead_id = @trainer_lead.id end if @trainer_lead_interview.save respond_to do |format| if @trainer_lead_interview.save # Tell the UserMailer to send a welcome email after save TrainerLeadInterviewMailer.with(@trainer_lead_interview).trainer_lead_interview(@trainer_lead_interview).deliver_now format.html # { redirect_to(@trainer_lead_interview, notice: 'Trainer Lead was successfully created.') } format.json # { render json: @trainer_lead_interview, status: :created, location: @trainer_lead_interview } # render json: {trainer_lead: @trainer_lead_interview} else format.html # { render action: 'new' } format.json # { render json: @trainer_lead_interview.errors, status: :unprocessable_entity } # render json: {error: @trainer_lead_interview.errors.messages.first}, status: 406 end end render json: {trainer_lead_interview: @trainer_lead_interview} else render json: {error: @trainer_lead_interview.errors.messages.first}, status: 406 end end def update @trainer_lead_interview = TrainerLeadInterview.find(params[:id]) if @trainer_lead_interview.update(params) render json: @trainer_lead_interview else render json: {error: @trainer_lead_interview.errors.messages.first[1][0]}, status: 406 end end def delete @trainer_lead_interview = TrainerLeadInterview.find(params[:id]) @trainer_lead_interview.destroy end private def trainer_lead_interview_params params.permit(:title, :interview_trainer_id, :trainer_id, :date, :location, :notes, :email_address, :first_name, :last_name, :phone_number, :licensed, :trainer_lead_interview=>{}) end end
# Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :sprint do start_at Date.today finish_at Date.today+15.days sprint_type 1 project end end
# == Schema Information # # Table name: reps # # id :integer not null, primary key # exercise_id :integer not null, foreign_key # qty :float not null # dt :date not null # created_at :datetime # updated_at :datetime # deleted_at :datetime # qty2 :float # qty3 :float class Rep < ApplicationRecord acts_as_paranoid # relations belongs_to :exercise # validations validates_presence_of :qty, :dt validates_numericality_of :qty, greater_than: 0 validates_numericality_of :qty2, greater_than: 0, allow_nil: true validates_numericality_of :qty3, greater_than: 0, allow_nil: true end
class AddCountryIdToUserInfo < ActiveRecord::Migration def change add_column :user_infos, :country_id, :integer add_column :user_infos, :state_id, :integer end end
class Record < ApplicationRecord validates :order, presence:true validates :name, presence:true validates :phone, presence:true validates :email, format: {with: /.*@.*/} end
module Api module V1 class ProductResource < JSONAPI::Resource attributes :name, :sold_out, :category, :under_sale, :price, :sale_price, :sale_text filters :category, :min_price, :max_price class << self def sortable_fields(context) super(context) + [:selling_price] end def selling_price_sql '*, CASE WHEN under_sale=true THEN sale_price ELSE price END AS selling_price' end def apply_sort(records, order_options, context = {}) order_options.each do |key, value| next if key != 'selling_price' records = records.select(selling_price_sql).order("selling_price #{value}") order_options.delete(key) end super(records, order_options, context) end def apply_filter(records, filter, value, _options) case filter when :min_price records.where('price >= ?', value) when :max_price records.where('price <= ?', value) else super(records, filter, value) end end end end end end
require 'rails_helper' module Annotable RSpec.describe 'Organizations', type: :request do context 'with organizations' do let!(:organization) { Fabricate(:organization) } describe 'GET /organizations' do it 'should return the collections' do get(organizations_path) expect(response).to have_http_status(:ok) expect(response_json['data'].size).to eq(1) expect(response_json['data'].first).to have_id(organization.id) expect(response_json['data'].first) .to have_attribute(:name).with_value(organization.name) end end describe 'GET /organizations/<UUID>' do it do get(organization_path(organization.id)) expect(response).to have_http_status(:ok) expect(response_json['data']).to have_id(organization.id) end end describe 'DELETE /organizations/<UUID>' do it 'should properly delete the resource' do expect do delete(organization_path(organization.id)) end.to change(Organization, :count).by(-1) expect(response).to have_http_status(:no_content) expect(response.body).to be_blank end end describe 'PUT-PATCH /organizations/<UUID>' do let(:params) do { data: { attributes: param_attributes } } end context 'with valid params' do let(:param_attributes) { Fabricate.attributes_for(:organization) } it 'should update properly the resource' do expect do put(organization_path(organization.id), params: params) end.to change { organization.reload.name }.from(organization.name).to(param_attributes[:name]) expect(response).to have_http_status(:ok) expect(response_json['data']).to have_id(organization.id) expect(response_json['data']) .to have_attribute(:name).with_value(param_attributes[:name]) end end context 'with invalid params' do let(:param_attributes) { { name: nil } } it 'should return the error message' do expect { put(organization_path(organization.id), params: params) }.not_to change(organization, :name) expect(response).to have_http_status(:unprocessable_entity) expect(response_json['errors'][0]['detail']).to eql("Name can't be blank") end end end end describe 'POST /organizations' do let(:params) do { data: { attributes: param_attributes } } end context 'with valid attributes' do let(:organization) { Organization.last } let(:param_attributes) do Fabricate.attributes_for(:organization) end it do expect do post(organizations_path, params: params) end.to change(Organization, :count).by(+1) expect(response).to have_http_status(:created) expect(response_json['data']).to have_id(organization.id) expect(response_json['data']) .to have_attribute(:name).with_value(param_attributes[:name]) end end context 'with invalid attributes' do let(:param_attributes) { { name: nil } } it 'should return the error message' do expect do post(organizations_path, params: params) end.not_to change(Organization, :count) expect(response).to have_http_status(:unprocessable_entity) expect(response_json['errors'][0]['detail']).to eql("Name can't be blank") end end end end end
class AddColumnToEducationalProgram < ActiveRecord::Migration def change add_column :educational_programs, :language, :string end end
module Searchable extend ActiveSupport::Concern class_methods do def search(attrs, &filter) logger.debug "Searchable::search filter: #{block_given?}" logger.debug attrs.to_yaml likes = [] data = [] attrs.each_pair { |(key, query)| if block_given? query = filter.call(key, query) end if !query.blank? likes << "#{key} LIKE ?" data << "%#{query}%" end } sql = likes.join(" AND ") self.where(sql, *data) end end end