text
stringlengths
10
2.61M
require 'yt/errors/request_error' module Yt module Errors class MissingAuth < RequestError def message <<-MSG.gsub(/^ {8}/, '') A request to YouTube API was sent without a valid authentication. #{more_details} MSG end def more_details if scopes && authentication_url && redirect_uri more_details_with_authentication_url elsif scopes && user_code && verification_url more_details_with_verification_url else more_details_without_url end end private def more_details_with_authentication_url <<-MSG.gsub(/^ {8}/, '') You can ask YouTube accounts to authenticate your app for the scopes #{scopes} by directing them to #{authentication_url}. After they provide access to their account, they will be redirected to #{redirect_uri} with a 'code' query parameter that you can read and use to build an authorized account object by running: Yt::Account.new authorization_code: code, redirect_uri: "#{redirect_uri}" MSG end def more_details_with_verification_url <<-MSG.gsub(/^ {8}/, '') Please authenticate your app by visiting the page #{verification_url} and entering the code #{user_code} before continuing. MSG end def more_details_without_url <<-MSG.gsub(/^ {8}/, '') If you know the access token of the YouTube you want to authenticate with, build an authorized account object by running: Yt::Account.new access_token: access_token If you know the refresh token of the YouTube you want to authenticate with, build an authorized account object by running: Yt::Account.new refresh_token: refresh_token MSG end def scopes @msg[:scopes] end def authentication_url @msg[:authentication_url] end def redirect_uri @msg[:redirect_uri] end def user_code @msg[:user_code] end def verification_url @msg[:verification_url] end end end end
class Api::V1::UsersController < ApplicationController before_action :find_user, only: [:show] def index @users = User.all render json: @users end def show render json: @user end def new @user = User.new end def create @user = User.create(user_params) if @user.valid? render json: @user else render json: { error: 'failed to create user' }, status: :not_acceptable end end private def user_params params.permit(:username, :password, :password_confirmation) end def find_user @user = User.find(params[:id]) end end
FactoryBot.define do factory :project do start_date { Date.current.next_occurring(:monday) } end_date { start_date + 6.days } sequence(:name) { |n| "Project-#{start_date.to_s(:long)}#{n > 0 ? ' - ' + n.to_s : ''}" } trait :with_sprints do transient do sprint_count { 4 } sprint_days { 2 } before(:create) do |project, evaluator| min_end_date = project.start_date + (evaluator.sprint_count * evaluator.sprint_days).days if project.end_date.before?(min_end_date) project.update!(end_date: min_end_date) end next_start_end_end_dates = lambda do |project, prev_sprint = nil| start_date = if prev_sprint prev_sprint.end_date.next_occurring(:monday) else project.start_date.monday? ? project.start_date : project.start_date.next_occurring(:monday) end end_date = start_date + evaluator.sprint_days.days project.end_date = end_date { start_date: start_date, end_date: end_date } end if evaluator.sprint_count >= 1 sprint = FactoryBot.build(:sprint, project: project, **next_start_end_end_dates.call(project)) project.end_date = sprint.end_date project.save! sprint.save! end if evaluator.sprint_count > 1 2.upto(evaluator.sprint_count) do sprint = FactoryBot.build(:sprint, project: project, **next_start_end_end_dates.call(project, Sprint.last)) project.end_date = sprint.end_date project.save! sprint.save! end end end end end trait :with_engineers do transient do engineer_count { 4 } members { FactoryBot.build_list(:engineer, engineer_count) } before(:create) do |project, evaluator| project.engineers << evaluator.members.to_a end end end end end
class SessionsController < Devise::SessionsController prepend_before_action :captcha_valid, only: [:create] skip_before_action :verify_authenticity_token, only: :create layout 'admin_lte_2_login' private def captcha_valid return true if verify_recaptcha redirect_to new_user_session_path, alert: "Recaptcha not verified" end end
require 'rails_helper' describe Api::V1::BookSuggestionController do describe 'POST #create' do context 'When creating a valid book suggestion' do let(:book_suggestion) { attributes_for(:book_suggestion) } it 'creates a new book suggestion' do expect { post :create, params: { book_suggestion: book_suggestion } }.to change(BookSuggestion, :count).by(1) end it 'responds with 201 status' do post :create, params: { book_suggestion: book_suggestion } expect(response).to have_http_status(:created) end end end end
module ApplicationHelper # Make a link to an icon. In the future the colour, size, and format # might come from application configuration. def make_icon_tag(image_name, opts={}) colour = "blue" size = "16x16" format = "png" file = if image_name == "blank" "blank.gif" else ["icons", format, colour, size, "#{image_name}.#{format}", ].join('/') end opts[:size] ||= size image_tag file, opts end end
# frozen_string_literal: true module Saucer class DataCollection PAGE_OBJECTS = %w[site_prism page-object watirsome watir_drops].freeze def gems ::Bundler.definition.specs.map(&:name).each_with_object({}) do |gem_name, hash| name = ::Bundler.environment.specs.to_hash[gem_name] next if name.empty? hash[gem_name] = name.first.version end end def page_objects page_objects_gems = PAGE_OBJECTS & gems.keys if page_objects_gems.size > 1 'multiple' elsif page_objects_gems.empty? 'unknown' else page_objects_gems.first end end def selenium_version gems['selenium-webdriver'] end def test_library if gems['watir'] && gems['capybara'] 'multiple' elsif gems['capybara'] 'capybara' elsif gems['watir'] 'watir' else 'unknown' end end def test_runner(runner) gems[runner.name.to_s] ? "#{runner.name} v#{gems[runner.name.to_s]}" : 'Unknown' end end end
require "test_helper" describe MerchantsController do describe "Logged in users" do before do @merchant = merchants(:merchantaaa) @merchant4 = merchants(:merchantddd) perform_login(@merchant) end describe "index" do it "responds with success when there are many merchants (without logging in)" do # Arrange (we have 4 merchants in the fixtures) num_of_merchants = Merchant.all.size # Act get merchants_path # Assert must_respond_with :success expect(num_of_merchants).must_equal 4 end it "responds with success when there are no merchants (without logging in)" do # Arrange Merchant.destroy_all num_of_merchants = Merchant.all.size # Act get merchants_path # Assert must_respond_with :success expect(num_of_merchants).must_equal 0 end end describe "account" do it "returns 200 for a logged-in user" do get account_path(@merchant.id) must_respond_with :success end it "redirect back to account if trying to access other merchant's account" do other_merchant = Merchant.last get account_path(other_merchant.id) must_redirect_to account_path(@merchant.id) expect(flash[:error]).must_equal "You don't have access to that account!" end it "redirect back to account if trying to access a not existed account" do get account_path(-1) expect(flash[:error]).must_equal "You don't have access to that account!" must_redirect_to account_path(@merchant.id) end it "logs in for diff user" do merchant_with_inactive = merchants(:merchantccc) perform_login(merchant_with_inactive) get account_path(merchant_with_inactive) must_respond_with :success end end describe "shop" do it "should return all products that belongs to one merchant" do get merchant_shop_path(@merchant.id) all_products_merchant = @merchant.products expect(all_products_merchant.length).must_equal 4 must_respond_with :success end it "will return empty array if we dont have any product for specific merchant" do perform_login(@merchant4) get merchant_shop_path(@merchant4.id) all_products_merchant = @merchant4.products expect(all_products_merchant.length).must_equal 0 must_respond_with :success end it "if merchant doesn't existing, redirect to root" do get merchant_shop_path(-1) expect(flash[:error]).must_equal "This merchant doesn't exist!" must_redirect_to root_path end end describe "order" do it "if merchant doesn't exist can not access to order history" do get merchant_orders_path(-1) expect(flash[:error]).must_equal "You don't have access to that account!" must_redirect_to root_path end it "A merchant can't access other merchant's order history" do get merchant_shop_path(@merchant.id) get merchant_orders_path(@merchant4.id) expect(flash[:error]).must_equal "You don't have access to that account!" must_redirect_to root_path end end describe "create(login as a merchant)" do let(:invalid_merchant) { Merchant.new( provider: "github", uid: "1234567", name: nil, email:"youknowwho@ada.org", avatar: "https://i.imgur.com/WSHmeuf.jpg" ) } let(:valid_merchant) { Merchant.new( provider: "github", uid: "1234567", name: "youknowwho", email:"youknowwho@ada.org", avatar: "https://i.imgur.com/WSHmeuf.jpg" ) } it "can log in" do must_respond_with :redirect must_redirect_to root_path end it "can log in a new user" do put logout_path, params: {} expect{logged_in_user = perform_login(valid_merchant)}.must_change "Merchant.count", 1 expect(Merchant.last.provider).must_equal valid_merchant[:provider] expect(Merchant.last.uid).must_equal valid_merchant[:uid] expect(Merchant.last.name).must_equal valid_merchant[:name] expect(Merchant.last.email).must_equal valid_merchant[:email] expect(Merchant.last.avatar).must_equal valid_merchant[:avatar] expect(flash[:notice]).must_equal "Logged in as a new merchant #{valid_merchant[:name].titleize}" must_respond_with :redirect must_redirect_to root_path end it "can't create merchant if merchant data is invalid" do put logout_path, params: {} OmniAuth.config.mock_auth[:github] = OmniAuth::AuthHash.new(mock_auth_hash(invalid_merchant)) get omniauth_callback_path(:github) expect(flash[:error]).must_equal "Could not create merchant account" must_redirect_to root_path end end describe "logout" do it "can logout an existing user" do put logout_path, params: {} expect(session[:merchant_id]).must_be_nil must_redirect_to root_path end end end describe "Guest users" do describe "index" do it "responds with success when there are many merchants (without logging in)" do # Arrange (we have 4 merchants in the fixtures) num_of_merchants = Merchant.all.size # Act get merchants_path # Assert must_respond_with :success expect(num_of_merchants).must_equal 4 end it "responds with success when there are no merchants (without logging in)" do # Arrange Merchant.destroy_all num_of_merchants = Merchant.all.size # Act get merchants_path # Assert must_respond_with :success expect(num_of_merchants).must_equal 0 end end describe "account" do it "redirect to root if trying to access other merchant's account" do other_merchant = Merchant.last get account_path(other_merchant.id) must_redirect_to root_path expect(flash[:error]).must_equal "You must be logged in to do that!" end it "redirect to root if trying to access a not existed account" do get account_path(1000000000) # merchant 1000000000 doesn't exist must_redirect_to root_path expect(flash[:error]).must_equal "You must be logged in to do that!" end end end end
describe ImmutableValidator do describe 'validation' do subject(:model) do model_class.new(attr: value) end let(:model_class) do Class.new(TestModel) do validates :attr, immutable: true end end let(:value) do 'foo' end context 'on create' do before do allow(model).to receive(:new_record?).and_return(true) allow(model).to receive(:attr_changed?).and_return(true) end it { should be_valid } end context 'on update' do before do allow(model).to receive(:new_record?).and_return(false) end context 'with change' do before do allow(model).to receive(:attr_changed?).and_return(true) end it { should be_invalid } end context 'without change' do before do allow(model).to receive(:attr_changed?).and_return(false) end it { should be_valid } end end end end
class Submission < ActiveRecord::Base # has_and_belongs_to_many :users has_many :submiss_users, :dependent => :destroy has_many :users, :through => :submiss_users has_many :authors, :dependent => :destroy has_many :specimens, :dependent => :destroy has_many :instruments has_many :spectra # has_many :spectral_feat_tbl_units validates_presence_of :title def is_locked? return self.submiss_status.to_s.downcase == 'submitted' || self.submiss_status.to_s.downcase == 'dumped' || self.submiss_status.to_s.downcase == 'exported' || self.submiss_status.to_s.downcase == 'accepted' || self.submiss_status.to_s.downcase == 'published' || self.submiss_status.to_s.downcase == 'revised-by-author' || self.submiss_status.to_s.downcase == 'original' end # is_locked? end # Submission
module Yaks module Reader class JsonAPI def call(parsed_json, _env = {}) included = parsed_json['included'].nil? ? {} : parsed_json['included'].dup if parsed_json['data'].is_a?(Array) CollectionResource.new( attributes: parsed_json['meta'].nil? ? nil : {meta: parsed_json['meta']}, members: parsed_json['data'].map { |data| call('data' => data, 'included' => included) } ) else attributes = parsed_json['data'].dup links = attributes.delete('links') || {} relationships = attributes.delete('relationships') || {} type = attributes.delete('type') attributes.merge!(attributes.delete('attributes') || {}) embedded = convert_embedded(Hash[relationships], included) links = convert_links(Hash[links]) Resource.new( type: Util.singularize(type), attributes: Util.symbolize_keys(attributes), subresources: embedded, links: links ) end end def convert_embedded(relationships, included) relationships.flat_map do |rel, relationship| # A Link doesn't have to contain a `data` member. # It can contain URLs instead, or as well, but we are only worried about *embedded* links here. data = relationship['data'] # Resource data MUST be represented as one of the following: # # * `null` for empty to-one relationships. # * a "resource identifier object" for non-empty to-one relationships. # * an empty array ([]) for empty to-many relationships. # * an array of resource identifier objects for non-empty to-many relationships. if data.nil? NullResource.new(rels: [rel]) elsif data.is_a? Array if data.empty? NullResource.new(collection: true, rels: [rel]) else CollectionResource.new( members: data.map { |link| data = included.find{ |item| (item['id'] == link['id']) && (item['type'] == link['type']) } call('data' => data, 'included' => included) }, rels: [rel] ) end else data = included.find{ |item| (item['id'] == data['id']) && (item['type'] == data['type']) } call('data' => data, 'included' => included).with(rels: [rel]) end end.compact end def convert_links(links) links.map do |rel, link| Resource::Link.new(rel: rel.to_sym, uri: link) end end end end end
require 'rails_helper' describe Friendship, type: :model do describe "validations" do it {should belong_to(:follower)} it {should belong_to(:followed)} end end
class User < ApplicationRecord has_many :book_progressions, dependent: :destroy has_many :books, through: :book_progressions has_secure_password validates :username, presence: true validates :email, presence: true, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i } validates :username, :email, uniqueness: true validates :password, presence: true def as_json(_options = nil) super(only: [ :email, :id, :username ]) end def slug self.username.downcase.split(" ").join("-") end def self.find_by_slug(slug) User.all.detect { |user| user.slug == slug } end end
class UsersController < ApplicationController before_action :logged_in_user, except: %i(show new create) before_action :load_user, except: %i(index new create) before_action :correct_user, only: %i(edit update) before_action :admin_user, only: :destroy before_action :load_follow, only: :show def index @users = User.actived.paginate page: params[:page], per_page: Settings.size.s_10 end def show redirect_to root_path && return unless @user.activated? @microposts = @user.microposts.paginate page: params[:page], per_page: Settings.size.s_10 end def edit; end def new @user = User.new end def create @user = User.new user_params if @user.save @user.send_activation_email flash[:success] = t ".welcome" redirect_to @user else render :new end end def update if @user.update_attributes user_params flash[:success] = t ".success" redirect_to @user else flash[:danger] = t ".danger" render :edit end end def destroy @user.destroy ? (flash[:success] = t ".success") : (flash[:danger] = t ".danger") redirect_to users_path end private def user_params params.require(:user).permit User::USER_TYPE end def load_user @user = User.find_by id: params[:id] return if @user flash[:danger] = t "users.danger_user" redirect_to root_path end # Confirms a logged-in user. def logged_in_user return if logged_in? store_location flash[:danger] = t "users.danger_login" redirect_to login_path end def correct_user return if current_user? @user redirect_to @user flash[:danger] = t "users.danger_permission" end def admin_user return if current_user.admin? redirect_to root_path flash[:danger] = t "users.danger_permission" end def load_follow @user_follow = current_user.active_relationships.build @user_unfollow = current_user.active_relationships .find_by(followed_id: @user.id) return if @user_follow || @user_unfollow redirect_to root_path flash[:danger] = t "users.danger_user" end end
class AddFixTimeToDefects < ActiveRecord::Migration def change add_column :defects, :fix_time, :integer, default: 0 end end
module SynapsePayRest # Represents social documents that can be added to a base document. # # @see https://docs.synapsepay.com/docs/user-resources#section-social-document-types # social document types class SocialDocument < Document; end end
Pod::Spec.new do |s| s.name = "WebSocketRails" s.version = "1.1.2" s.summary = "WebSocketRails client for iOS." s.description = <<-DESC Port of JavaScript client provided by https://github.com/websocket-rails/websocket-rails Built on top of SocketRocket. There is a sample WebSocketRails server located here https://github.com/patternoia/WebSocketRailsEcho One can use it to test various WebSocketRocket event types. DESC s.homepage = "https://github.com/patternoia/WebSocketRails-iOS" s.license = { :type => "MIT", :file => "LICENSE" } s.author = "patternoia" s.social_media_url = "http://github.com/patternoia" s.platform = :ios, "7.0" s.source = { :git => "https://github.com/patternoia/WebSocketRails-iOS.git", :tag => "1.1.1" } s.source_files = "WebSocketRails-iOS/*.{h,m}" s.library = "icucore" s.requires_arc = true s.dependency "SocketRocket", "~> 0.3.1-beta2" end
require "spec_helper" describe "Session", type: :request do describe "log in with email" do before do identity = create(:identity) get( "/api/auth/identity/callback", { auth_key: identity.email, password: identity.password, name: "NAME#{rand(1000)}" }) end it "should respond with status 200" do expect(response.status).to eq(200) end end describe "failure to log in with email" do before do get( "/api/auth/identity/callback", { auth_key: nil }) end it "should respond with invalid credentials" do expect(response.headers["Location"]).to include("invalid_credentials") end end describe "log in with facebook" do before do OmniAuth.config.test_mode = true OmniAuth.config.add_mock( :facebook, { uid: "1234", info: { email: "USER#{rand(1000)}@FITBIRD.COM" }}) Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:facebook] get("/api/auth/facebook/callback") end it "should respond with status 200" do expect(response.status).to eq(200) end end describe "log out" do before do user = create(:user) login(user) get("/api/logout") end it "should respond with status 200" do expect(response.status).to eq(200) end end end
unified_mode true # # Cookbook:: graphite # Resource:: storage # # Copyright:: 2014-2016, Heavy Water Software Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # property :prefix, String, name_property: true property :package_name, String, default: 'whisper' property :version, String property :type, String, default: 'whisper' action :create do manage_python_pip(:install) manage_directory(:create) end action :upgrade do manage_python_pip(:upgrade) manage_directory(:create) end action :delete do manage_python_pip(:remove) manage_directory(:delete) end action_class do def manage_python_pip(resource_action) python_package new_resource.package_name do version new_resource.version if new_resource.version Chef::Log.info 'Installing whisper pip package' action resource_action user node['graphite']['user'] group node['graphite']['group'] install_options '--no-binary=:all:' virtualenv node['graphite']['base_dir'] end end def manage_directory(resource_action) directory new_resource.prefix do recursive true Chef::Log.info "Removing storage path: #{new_resource.prefix}" action resource_action end end end
require 'test_helper' class ContatosControllerTest < ActionController::TestCase setup do @contato = contatos(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:contatos) end test "should get new" do get :new assert_response :success end test "should create contato" do assert_difference('Contato.count') do post :create, contato: { email: @contato.email, nome: @contato.nome, obs: @contato.obs, tipo_id: @contato.tipo_id } end assert_redirected_to contato_path(assigns(:contato)) end test "should show contato" do get :show, id: @contato assert_response :success end test "should get edit" do get :edit, id: @contato assert_response :success end test "should update contato" do patch :update, id: @contato, contato: { email: @contato.email, nome: @contato.nome, obs: @contato.obs, tipo_id: @contato.tipo_id } assert_redirected_to contato_path(assigns(:contato)) end test "should destroy contato" do assert_difference('Contato.count', -1) do delete :destroy, id: @contato end assert_redirected_to contatos_path end end
class Excercise < ActiveRecord::Base attr_accessible :name, :reps, :routine_day_id, :series, :excercise_name belongs_to :routine_day belongs_to :single_excercise def excercise_name self.single_excercise.try(:name) end def excercise_name=(name) self.single_excercise = SingleExcercise.find_or_create_by_name(name) if name.present? end end
module Fog module Google class SQL ## # Creates a new backup run on demand. This method is applicable only to Second # Generation instances. # # @see https://cloud.google.com/sql/docs/mysql/admin-api/v1beta4/backupRuns/insert class Real def insert_backup_run(instance_id, backup_run = {}) @sql.insert_backup_run( @project, instance_id, ::Google::Apis::SqladminV1beta4::BackupRun.new(**backup_run) ) end end class Mock def insert_backup_run(_instance_id, _run) # :no-coverage: Fog::Mock.not_implemented # :no-coverage: end end end end end
class RateLimiter MAX_REQUESTS_PER_PERIOD = 60 * 5 * 3 TIME_PERIOD_IN_SECONDS = 60 * 5 BASE_REDIS_KEY = 'request-count-ip' def self.should_block_request?(ip) recent_requests(ip).to_i >= MAX_REQUESTS_PER_PERIOD end def self.incr_requests(ip) Redis.current.multi do |multi| multi.incr(redis_key(ip)) multi.expire(redis_key(ip), TIME_PERIOD_IN_SECONDS) end end def self.recent_requests(ip) Redis.current.get(redis_key(ip)) end def self.block_requests(ip, seconds = TIME_PERIOD_IN_SECONDS) Redis.current.set(redis_key(ip), MAX_REQUESTS_PER_PERIOD, ex: seconds) end def self.redis_key(ip) "#{BASE_REDIS_KEY}-#{ip}-#{TIME_PERIOD_IN_SECONDS}-#{Time.current.to_i / TIME_PERIOD_IN_SECONDS}" end end
FactoryGirl.define do factory :product, class: Hash do initialize_with { { 'id' => '123', 'type' => 'products', 'attributes' => { 'name' => 'My Awesome Tablet', 'part_number' => '1234-9999', 'brand_name' => 'Tablet Maker', 'category_name' => 'Tablets', 'product_status' => 'NEW', 'manufacturer_suggested_retail_price' => '12.34', 'estimated_retail_price' => '12.34', 'net_estimated_price' => '12.34', 'average_online_price' => '12.34', 'average_retail_dot_com_net_price' => '12.34', 'average_retail_dot_com_weekly_net_price' => '12.34', 'average_retail_net_price' => '12.34', 'average_retail_weekly_net_price' => '12.34', 'average_ecom_net_price' => '12.34', 'average_ecom_weekly_net_price' => '12.34', 'most_frequent_price' => '12.34', 'most_frequent_weekly_price' => '12.34', 'most_frequent_monthly_price' => '12.34', 'most_frequent_retail_weekly_price' => '12.34', 'most_frequent_retail_net_price' => '12.34', 'links' => { 'self' => 'http://api.gapintelligence.com/api/v1/products/123' }, 'image_url' => 'https://gapi-production.s3.amazonaws.com/uploads/product/image/123/image.jpeg' } } } end end
# frozen_string_literal: true # == Schema Information # # Table name: books # # id :bigint(8) not null, primary key # base_price :integer # image_content_type :string # image_file_name :string # image_file_size :integer # image_updated_at :datetime # release_date :date # title :string # created_at :datetime not null # updated_at :datetime not null # format_id :bigint(8) # # Indexes # # index_books_on_format_id (format_id) # FactoryBot.define do factory :book do sequence(:title) {|n| "Name #{n}" } release_date Date.today base_price 100 format_id Format.first.id image { File.new(Rails.root.join('app', 'assets', 'images', 'image.jpeg')) } after(:create) do |book| create(:book_author, book: book) end end end
# -*- encoding: utf-8 -*- require File.expand_path('../lib/altum/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Larry Marburger"] gem.email = ["larry@marburger.cc"] gem.description = %q{Drive ShowOff remotely} gem.summary = %q{Altum uses the magic of Pusher and websockets to drive a ShowOff presentation remotely. The simplest tool to walk through a deck on a conference call.} gem.homepage = "http://lmarburger.github.com/altum/" gem.add_dependency 'pusher' gem.add_dependency 'rack' gem.add_development_dependency 'rake' gem.add_development_dependency 'webmock' gem.add_development_dependency 'wrong' gem.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } gem.files = `git ls-files`.split("\n") gem.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") gem.name = "altum" gem.require_paths = ["lib"] gem.version = Altum::VERSION end
class EasyRakeTasksController < ApplicationController layout 'admin' before_filter :find_easy_rake_task, :except => [:index, :new, :create] helper :easy_rake_tasks include EasyRakeTasksHelper def index @tasks = EasyRakeTask.all end def new @task = params[:type].constantize.new if params[:type] unless @task.is_a?(EasyRakeTask) render_404 return end @task.safe_attributes = params[:easy_rake_task] respond_to do |format| format.html end end def create @task = params[:type].constantize.new if params[:type] unless @task.is_a?(EasyRakeTask) render_404 return end @task.safe_attributes = params[:easy_rake_task] if @task.save respond_to do |format| format.html { flash[:notice] = l(:notice_successful_create) redirect_back_or_default(:action => :index) } end else respond_to do |format| format.html { render :action => :new } end end end def edit respond_to do |format| format.html end end def update @task.safe_attributes = params[:easy_rake_task] if @task.save respond_to do |format| format.html { flash[:notice] = l(:notice_successful_update) redirect_back_or_default(:action => :index) } end else respond_to do |format| format.html { render :action => :edit } end end end def task_infos @task_infos_ok = @task.easy_rake_task_infos.status_ok.limit(10).order("#{EasyRakeTaskInfo.table_name}.started_at DESC").all @task_infos_failed = @task.easy_rake_task_infos.status_failed.limit(10).order("#{EasyRakeTaskInfo.table_name}.started_at DESC").all end def destroy if @task.deletable? @task.destroy flash[:notice] = l(:notice_successful_delete) end respond_to do |format| format.html { redirect_back_or_default :action => 'index' } end end def execute #begin @task.class.execute_task(@task) #rescue #end redirect_to({:controller => 'easy_rake_tasks', :action => :task_infos, :id => @task, :back_url => params[:back_url]}) end def easy_rake_task_info_detail_receive_mail info_detail = EasyRakeTaskInfoDetailReceiveMail.find(params[:easy_task_info_detail_id]) render :partial => 'easy_rake_tasks/info_detail/easy_rake_task_info_detail_receive_mail', :locals => {:task => @task, :info_detail => info_detail} end def easy_rake_task_easy_helpdesk_receive_mail_status_detail status = params[:status] offset = params[:offset].to_i limit = 10 details = EasyRakeTaskInfoDetailReceiveMail.includes(:easy_rake_task_info).where(["#{EasyRakeTaskInfo.table_name}.easy_rake_task_id = ? AND #{EasyRakeTaskInfoDetailReceiveMail.table_name}.status = ?", @task, status]).order("#{EasyRakeTaskInfo.table_name}.finished_at DESC").limit(limit).offset(offset).all respond_to do |format| format.js { render :partial => 'easy_rake_tasks/additional_task_info/easy_rake_task_easy_helpdesk_receive_mail_status_detail', :locals => {:task => @task, :details => details, :status => status, :offset => offset + limit} } end end private def find_easy_rake_task @task = EasyRakeTask.find(params[:id]) rescue ActiveRecord::RecordNotFound render_404 end end
class App::Dashboards::BookHistoriesController < App::DashboardsController before_action :set_date_params def index @book_histories = BookHistory .includes(book: [:subject, :publisher], details: :book_unit) .where(match_id: params[:dashboard_id]).original_only.between(@start_date, @end_date) end def new @book_history = BookHistory.new(match_id: params[:dashboard_id]) end def list return if book_list_params[:subject_id].blank? || book_list_params[:book_publisher_id].blank? @books = Standard::Book.where(book_list_params) end def create @book_history = BookHistory.new(book_history_params) @book_history.create_histories(book_history_params) return if @book_history.save render :new end def edit @book_history = BookHistory.includes(:book, details: :book_unit).find_by(id: params[:id], match_id: params[:dashboard_id]) end def change_period @book_history = BookHistory.find(params[:id]) @book_history.update(book_history_change_period_params) render :edit end def update @book_history = BookHistory.find(params[:id]) @book_history_detail = BookHistory.find(params[:detail_id]) if @book_history_detail.update(book_history_update_params) @book_history.reload else render :edit end end def rating @book_history = BookHistory.find(params[:id]) @book_history.update(rating: params[:rating]) head :ok end private def book_history_params params .fetch(:book_history, {}) .permit(:match_id, :subject_id, :book_publisher_id, :book_id, :started_at, :planned_at) end def book_list_params params .fetch(:book_history, {}) .permit(:subject_id, :book_publisher_id) end def book_history_change_period_params params .fetch(:book_history, {}) .permit(:tag_color, :started_at, :planned_at) end def book_history_update_params params .permit(:planned_at, :completed_at) end end
class Bonu < ActiveRecord::Base has_many :donations end
class ApplicationController < ActionController::Base include Pundit protect_from_forgery with: :exception rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized def markdown_renderer HTML::Pipeline.new([ HTML::Pipeline::MarkdownFilter, HTML::Pipeline::SanitizationFilter, HTML::Pipeline::SyntaxHighlightFilter ], gfm: true) end def after_sign_in_path_for(resource) return '/admin' if Admin === resource super end private def user_not_authorized flash[:alert] = "Brak uprawnień" redirect_to(request.referrer || root_path) end end
class NotesController < ApplicationController def index @workshop = Workshop.find(params[:workshop_id]) @notes = policy_scope(Note).where(workshop: @workshop) end def new @workshop = Workshop.find(params[:workshop_id]) @notes = policy_scope(Note).where(workshop: @workshop) @note = Note.new @note.workshop = @workshop @note.user = current_user authorize @note end def edit @workshop = Workshop.find(params[:workshop_id]) @notes = policy_scope(Note).where(workshop: @workshop) @note = Note.find(params[:id]) authorize @note end def destroy @workshop = Workshop.find(params[:workshop_id]) @note = Note.find(params[:id]) authorize @note if @note.destroy redirect_to workshop_notes_path(@workshop), notice: 'Note deleted' else @notes = policy_scope(Note).where(workshop: @workshop) render :index end end def update @workshop = Workshop.find(params[:workshop_id]) @note = Note.find(params[:id]) authorize @note if @note.update(note_params) redirect_to workshop_notes_path(@workshop), notice: 'Note updated' else @notes = policy_scope(Note).where(workshop: @workshop) render :index end end def create @workshop = Workshop.find(params[:workshop_id]) @note = Note.new(note_params) @note.workshop = @workshop @note.user = current_user authorize @note if @note.save! redirect_to workshop_notes_path(@workshop) else @notes = policy_scope(Note).where(workshop: @workshop) render :index end end private def note_params params.require(:note).permit(:content, :title) end end
require 'rails_helper' RSpec.describe Manage, :type => :model do it "its OK when name, price, ingredient and pictures attributes exists" do prato = Manage.new( name: 'File', price: 'R$ 100,00', ingredient: 'carne', pictures: "/app/assets/images/foto_pratos/Lasanha.jpg" ) expect(prato).to be_valid end it "is invalid when havent a name" do prato = Manage.new(name: nil) expect(prato).to be_invalid end it "is invalid when name already exists in database, name have to be unique" do prato = Manage.create( name: 'porco', price: 'R$100,00', ingredient: 'feijão' ) prato = Manage.new( name: 'porco', price: 'R$80,00', ingredient: 'arroz' ) expect(prato).to be_invalid end it "is invalid when name length is greater than 50" do prato = Manage.new(name: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", price:'R$80,00', ingredient: 'abc') expect(prato).to be_invalid end it "is invalid when price length is greater than 10" do prato = Manage.new(name: "ave", price: "aaaaaaaaaaa", ingredient: 'abcd') expect(prato).to be_invalid end it "is invalid when ingredient length is greater than 200" do prato = Manage.new(name: "boi", ingredient: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", price:'R$89,00') expect(prato).to be_invalid end end
class TasksController < ApplicationController before_action :authenticate_user def new @task = Task.new end def create @task = Task.new(task_params) @task.user = current_user if @task.save flash[:notice]= "新規登録しました!" redirect_to tasks_path else render "new" end end def index else @tasks = Task.all.order(created_at: "DESC").page(params[:page]) end end def search if params[:task][:name].present? && params[:task][:status].present? @tasks = Task.name_status_search(params[:task][:name], params[:task][:status]) flash[:notice] = "タイトルとステータスで絞り込みました。" render "index" elsif params[:task][:name].present? @tasks = Task.name_search(params[:task][:name]) flash[:notice] = "タイトルで絞り込みました。" render "index" elsif params[:task][:status].present? @tasks = Task.status_search(params[:task][:status]) flash[:notice] = "ステータスで絞り込みました。" render "index" else @tasks = Task.all flash[:notice] = "検索項目を入力してください。" render "index" end end def edit @task = Task.find(params[:id]) end def update @task = Task.find(params[:id]) @task.update(task_params) flash[:notice]= "編集しました!" redirect_to tasks_path end def show @task = Task.find(params[:id]) end def destroy @task = Task.find(params[:id]) @task.destroy flash[:notice]= "削除しました!" redirect_to tasks_path end private def task_params params.require(:task).permit(:name,:content,:expired_date,:status,:priority) end end
module Resourced class Sequence < SerializedWithType include Router def initialize(uri, data, type, application_context, options={}) @uri = uri @data = data @type = type @application_context = application_context @max_length = options[:max_length] end attr_reader :max_length route "/range/{begin}-{end}", :name => 'range', :regexps => {:begin => /\d+/, :end => /\d+/} do |router, matched_uri, params| router.range_resource(matched_uri, params[:begin].to_i, params[:end].to_i) end route "/range/all", :name => 'all_items' do |router, matched_uri| router.all_items_resource(matched_uri) end def range_resource(uri, first, last) length = last-first+1 if length >= 0 && (!max_length || length <= max_length) SerializedWithType.new(uri, @data, @type.with_options(:slice => first..last), @application_context) end end def all_items_resource(uri) SerializedWithType.new(uri, @data, @type.with_options(:slice => nil), @application_context) unless max_length end end end
class AddFather < ActiveRecord::Migration def change change_table(:people) do |t| t.column :father_id, :int end end end
class Ivoice < ActiveRecord::Migration[5.2] def change create_table :invoices do |t| t.float :amount, null:false t.string :company, null:false t.string :contragent, null:false t.string :currency, :default => 'USD' t.date :date t.timestamps null: false end end end
require "rails_helper" feature "As visitor I can't" do scenario "create article" do visit articles_path expect(page).not_to have_button("Create Article") end end
# encoding: UTF-8 # 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) User.destroy_all Role.destroy_all Classroom.destroy_all Teacher.destroy_all Kid.destroy_all Mental.destroy_all Interest.destroy_all KindAccount.destroy_all Bank.destroy_all AgeGroup.destroy_all ClassRegistration.destroy_all roles = ["Admin","Kid","User","Teacher", "Accountant"] p "creating Roles" roles.each do |role| p " #{role}" if Role.where(:name => role).blank? Role.create(:name => role) p '+' else p '=' end end p "creating users" users = [ {:email => "admin@ms.com", :password => "1234567890", :name => "مدیر سیستم" }, {:email => "user@ms.com", :password => "1234567890", :name => "کاربر", :last_name => "عادی" }, {:email => "kid@ms.com", :password => "1234567890", :name => "کودک"}, {:email => "teacher@ms.com",:password => "1234567890", :name => "مربی"}, {:email => "learning@ms.com",:password => "1234567890", :name => "مربی پرورشی"}, {:email => "m_mw@ms.com",:password => "1234567890", :name => "مهسا", :last_name => "پورجعفریان", :sex => "مونث", :address => "مشهد- بلوار پیروزی- پیروزی ۵- دعبل خزایی ۷- پلاک ۱۳۴", :phone => "8783863", :mobile_no => "9153031943", :father_name => "علی", :category_id => 2, :identify_code => "653167393" }, {:email => "accountant@ms.com",:password => "1234567890", :name => "حسابدار"}, ] 40.times{|i| users << {:email => "user#{i}@ms.com", :password => "1234567890", :name => "user#{i}" }} users.each do |user| p user[:email] if User.where(:email => user[:email]).blank? u = User.new(user) u.confirmed_at = DateTime.now p "+" if u.save else p "=" end end p "setting Roles" User.where(:email => "admin@ms.com").first.roles = [Role.where(:name => "Admin").first] User.where(:email => "user@ms.com").first.roles = [Role.where(:name => "User").first] User.where(:email => "kid@ms.com").first.roles = [Role.where(:name => "Kid").first] User.where(:email => "teacher@ms.com").first.roles= [Role.where(:name => "Teacher").first] User.where(:email => "learning@ms.com").first.roles= [Role.where(:name => "Teacher").first] User.where(:email => "m_mw@ms.com").first.roles= [Role.where(:name => "Kid").first] User.where(:email => "accountant@ms.com").first.roles= [Role.where(:name => "Accountant").first] p "creating persons" User.all.each do |u| u.create_person end p 'createing age groups' AgeGroup.create(:title => "کودکان") AgeGroup.create(:title => "نونهالان") p "createing Classrooms" teacher_id = Teacher.first.id age_group_id = AgeGroup.first.id Classroom.create("name"=>"کلاس ۱", "start_time"=> Date.today, "end_time"=> Date.today + 6.month, "capacity"=>40, "teacher_id"=>teacher_id, "age_group_id"=>age_group_id, "class_type"=>1, "price"=>1000 ) Classroom.create("name"=>"کلاس ۲", "start_time"=> Date.today, "end_time"=> Date.today + 6.month, "capacity"=>20, "teacher_id"=>teacher_id, "age_group_id"=>age_group_id, "class_type"=>1, "price"=>2000 ) Classroom.create("name"=>"کلاس 3", "start_time"=> Date.today, "end_time"=> Date.today + 6.month, "capacity"=>10, "teacher_id"=>teacher_id, "age_group_id"=>age_group_id, "class_type"=>2, "price"=>3000 ) Rake::Task['db:add_default_pages'].invoke p "createing Bank info" Bank.create(:title => "ملت") p "createing KindAccounts info" KindAccount.create(:owner_name => "مهدکودک باغ ستاره ها", :number => "1234 5678 1245 45678", :bank_id => 1) p "createing Interest info" Interest.create(:title => "خمیربازی") Interest.create(:title => "بازی فکری") p "createing mentals info" Mental.create(:title => "استرسی") Mental.create(:title => "بیش فعالی")
class BuyersController < ApplicationController def show @buyer = Buyer.find(params[:id]) end end
class CreateFeedback < ActiveRecord::Migration def change create_table :feedbacks do |t| t.text :continue_doing t.text :improve_upon t.text :appreciation t.string :given_by t.belongs_to :user end end end
class Post < ActiveRecord::Base validates :user_id, :title, :body, presence: true belongs_to :user scope :for_anyone, -> { where(member_only: false) } scope :order_updated_at , ->{ order('updated_at desc')} end
# frozen_string_literal: true # Seo Model class Seo < ApplicationRecord include ActivityHistory include CloneRecord include Uploadable include Downloadable include Sortable acts_as_list acts_as_paranoid # Fields for the search form in the navbar def self.search_field fields = %i[position deleted_at] build_query(fields, :or, :cont) end # Funcion para armar el query de ransack def self.build_query(fields, operator, conf) query = fields.join("_#{operator}_") query << "_#{conf}" query.to_sym end def self.sitemap_code file = "#{Rails.root}/config/sitemap.rb" index_html = File.readlines(file) index_html.join('') end def self.robots_code file = "#{Rails.root}/public/robots.txt" index_html = File.readlines(file) index_html.join('') end def self.save_sitemap(code) file = "#{Rails.root}/config/sitemap.rb" File.write(file, code) system "ruby #{Rails.root}/config/sitemap.rb" end def self.save_robots(code) file = "#{Rails.root}/public/robots.txt" File.write(file, code) end end
class Jurisdiction < ActiveRecord::Base has_many :services validates_presence_of :name end
require 'test/unit' require_relative '../src/parser' class ParserTest < Test::Unit::TestCase def test_parser code = <<-CODE def method(a, b): b() def b(): false CODE nodes = Nodes.new([ DefNode.new("method", ["a", "b"], Nodes.new([ CallNode.new(nil, "b", []) ]) ), DefNode.new("b",[], Nodes.new([ FalseNode.new ]) ) ]) assert_equal nodes, Parser.new.parse(code) end end
begin config = YAML.load_file(Rails.root.join('config', 'letsencrypt_plugin.yml')) config.merge! config.fetch(Rails.env, {}) LetsencryptPlugin.config = config rescue Errno::ENOENT LetsencryptPlugin.config_file = Rails.root.join('config', 'letsencrypt_plugin.yml') end
require 'ruby-kong-auth/requests/key_auth' module RubyKongAuth class KeyAuth < Model attr_accessor :id, :consumer_id, :key, :created_at, :errors class << self # Params: consumer_id # # Usage: RubyKongAuth::KeyAuth.all(consumer_id: 'xxx') def all(*args) request = RubyKongAuth::Request::KeyAuth.list args[0] if request.code == 200 data = [] request.body['data'].each do |key_auth| data << KeyAuth.new(KeyAuth.symbolize_keys!(key_auth)) end data else [] end end # Params: consumer_id, key_auth_id # # Usage: RubyKongAuth::KeyAuth.find consumer_id: 'xxx', # id: 'xxx' def find(*args) request = RubyKongAuth::Request::KeyAuth.retrieve args[0] if request.code == 200 KeyAuth.new(symbolize_keys!(request.body)) else nil end end end # Get key auth consumer # Usage: key_auth = RubyKongAuth::KeyAuth.find consumer_id: 'xxx', # id: 'xxx' # consumer = key_auth.consumer def consumer RubyKongAuth::Consumer.find(consumer_id: self.consumer_id) end # Create key auth # Required params: consumer_id # Usage: key_auth = RubyKongAuth::KeyAuth.new consumer_id: 'xxx' # key_auth.save def save(*args) requires :consumer_id request = RubyKongAuth::Request::KeyAuth.create consumer_id: self.consumer_id if request.code == 201 request.body.each do |key, value| send("#{key.to_s}=", value) rescue false end true else send("errors=", [request.body['message']]) false end end # Destroy key auth # Required params: consumer_id, :key_auth_id # Usage: key_auth = RubyKongAuth::KeyAuth.find consumer_id: 'xxx', # key_auth_id: 'xxx' # key_auth.destroy def destroy(*args) request = RubyKongAuth::Request::KeyAuth.destroy consumer_id: self.consumer_id, id: self.id if request.code == 204 true else self.errors = [request.body['message']] false end end end end
module Rounders module Generators class AppGenerator < Base argument :name, type: :string argument :path, type: :string, required: false def set_destination_root p = path.nil? ? name : File.join(path, name) self.destination_root = p end def create_directory directory('app') directory('config') end def test directory('spec') end def readme template 'README.md' end def gemfile template 'Gemfile' end def license template 'MIT-LICENSE' end def gitignore template 'gitignore', '.gitignore' end def travis template 'travis.yml', '.travis.yml' end def rakefile template 'Rakefile' end end end end
class RenameRailsProjectsFields < ActiveRecord::Migration[5.0] def change rename_column :projects, :adapter, :database_adapter rename_column :projects, :database, :database_name rename_column :projects, :username, :database_username rename_column :projects, :password, :database_password end end
# Problem # Select the element out of the array if its index is a fibonacci number # Any one fibonacci number is the sum of the two fibonacci numbers that come before it # input: Array # output: Array with only the elements whose index in the input Array was a fibonacci number (starting with 1, not 0) # Examples / Test Cases # Fibonacci sequence: # 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, etc... # alphabet = ("a".."z").to_a # names = ['Nathan', 'Jeanette', 'Joshua', 'Daniel', 'Mark', 'Laura', 'Daniel', 'Kaluah', 'Goober'] # p fibs_index(alphabet) == ['a', 'b', 'c', 'd', 'f', 'i', 'n', 'v'] # p fibs_index(names) == ['Nathan', 'Jeanette', 'Joshua', 'Daniel', 'Laura', 'Goober'] # Algorithm # Take the size of the array # Create an array with the number of fibonaci numbers up to that number # Take an array with 0, and 1, add the last two elements together, push that to the array. repeat. # Select the items in the array with the index of the fib nums. def fibs_index(arr) fibs = [0, 1] until fibs[-1] > arr.size fibs << fibs[-1] + fibs[-2] end arr.select.with_index {|item, index| fibs.include?(index)} end alphabet = ("a".."z").to_a names = ['Nathan', 'Jeanette', 'Joshua', 'Daniel', 'Mark', 'Laura', 'Daniel', 'Kaluah', 'Goober'] # p fibs_index(alphabet) p fibs_index(alphabet) == ['a', 'b', 'c', 'd', 'f', 'i', 'n', 'v'] p fibs_index(names) == ['Nathan', 'Jeanette', 'Joshua', 'Daniel', 'Laura', 'Goober']
require 'spec_helper' describe Request::Protocol, '.get' do let(:object) { described_class } subject { object.get(input) } context 'with "http"' do let(:input) { 'http' } it { should eql(Request::Protocol::HTTP) } end context 'with "https"' do let(:input) { 'https' } it { should eql(Request::Protocol::HTTPS) } end context 'with "ftp"' do let(:input) { 'ftp' } it 'should raise error' do # jruby has different message format expectation = begin {}.fetch('ftp') rescue KeyError => error error end expect { subject }.to raise_error(KeyError, expectation.message) end end end
class CreateGroupByDimension < ActiveRecord::Migration def change create_table :groupings do |t| t.integer :algorithm_id t.integer :priority t.string :dimension1 t.string :dimension2 end end end
require './lib/word_finder' class Scrabble def score(word) valid_word?(word) ? score_word(word) : 0 end def score_word(word) word.each_char.map do |letter| get_letter_point(letter) end.reduce(0, :+) end def get_letter_point(letter) valid_letter?(letter) ? point_values[validate(letter)] : 0 end def validate(letter) letter.upcase end def valid_letter?(letter) ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"].include?(letter) end def valid_word?(word) word_finder = WordFinder.new word_finder.words.include?(word) end def point_values { "A"=>1, "B"=>3, "C"=>3, "D"=>2, "E"=>1, "F"=>4, "G"=>2, "H"=>4, "I"=>1, "J"=>8, "K"=>5, "L"=>1, "M"=>3, "N"=>1, "O"=>1, "P"=>3, "Q"=>10, "R"=>1, "S"=>1, "T"=>1, "U"=>1, "V"=>4, "W"=>4, "X"=>8, "Y"=>4, "Z"=>10 } end def score_with_multipliers(word, multipliers, word_multiplier=1) if word.length != 7 score_with_multiplier(word, multipliers) * word_multiplier else (score_with_multiplier(word, multipliers) + 10) * word_multiplier end end def score_with_multiplier(word, multipliers) word.chars.map.with_index do |letter, index| get_letter_point(letter) * multipliers[index] end.reduce(:+) end end
module Slack module Aria class Alice < Undine class << self def name 'アリス・キャロル' end def icon 'https://raw.githubusercontent.com/takesato/slack-aria/master/image/alice120x120.jpg' end end Company.client.on :message do |data| if(data['type'] == 'message' && data['subtype'] == 'file_share') if data['file']['size'] >= 2097152 Alice.speak(data['channel'], "<@#{data['user']}> でっかいファイルです") end end end end end end
Pod::Spec.new do |s| s.name = "QLZ_MultiPageViewController" s.version = "0.1.1" s.summary = "iOS Multi Page ViewController." s.homepage = "https://github.com/qlz130514988/QLZ_MultiPageViewController" s.license = { :type => "MIT", :file => "LICENSE" } s.author = { "qlz130514988." => "https://github.com/qlz130514988" } s.platform = :ios, "7.0" s.source = { :git => 'https://github.com/qlz130514988/QLZ_MultiPageViewController.git', :tag => s.version, :submodules => true } s.source_files = "QLZ_MultiPageViewController/*.{h,m}" s.frameworks = "Foundation" s.requires_arc = true s.dependency "QLZ_Categories", "~> 0.1.6" end
module Rucksack module Packer class Jsmin < Rucksack::Packer::Base supports :javascripts JSMIN = "#{File.dirname(__FILE__)}/../../../vendor/jsmin.rb" def pack(source, target) `ruby #{JSMIN} < #{source} > #{target}\n` end end end end
#============================================================================== # +++ MOG - Simple Diagonal Movement (v1.0) +++ #============================================================================== # By Moghunter # http://www.atelier-rgss.com #============================================================================== # Sistema simples de movimento na diagonal. #============================================================================== #============================================================================== # ■ Diagonal Movement #============================================================================== class Game_Player < Game_Character #-------------------------------------------------------------------------- # ● Move By Input #-------------------------------------------------------------------------- def move_by_input return unless movable? return if $game_map.interpreter.running? case Input.dir8 when 2,4,6,8; move_straight(Input.dir4) when 1 move_diagonal(4, 2) unless moving? move_straight(4) move_straight(2) end when 3 move_diagonal(6, 2) unless moving? move_straight(6) move_straight(2) end when 7 move_diagonal(4, 8) unless moving? move_straight(4) move_straight(8) end when 9 move_diagonal(6, 8) unless moving? move_straight(6) move_straight(8) end end end end $mog_rgss3_simple_diagonal_movement = true
class AddManeuverIndex < ActiveRecord::Migration def change add_index :maneuvers, :name, :unique => true end end
class SpecialistGroupsController < InheritedResources::Base has_scope :by_specialization, as: :specialization, only: [:index] load_and_authorize_resource before_filter :decorate_collection, only: :index before_filter :decorate_resource, except: :index private def decorate_collection set_collection_ivar( SpecialistGroupDecorator.decorate_collection(get_collection_ivar) ) end def decorate_resource set_resource_ivar( SpecialistGroupDecorator.decorate(get_resource_ivar) ) end def page_subtitle if params[:action] == 'index' if !params[:specialization] || params[:specialization].match(/^all$/i) 'Все специалисты' else I18n.t "specialists.#{params[:specialization].pluralize}.title" end else I18n.t "specialists.#{resource.specialization.pluralize}.title" end end end
#!/usr/bin/env ruby -rubygems # -*- encoding: utf-8 -*- require 'date' Gem::Specification.new do |s| s.version = '0.0.1dev' s.date = Date.today.to_s s.name = 'kosa' s.homepage = 'https://github.com/ieru/kosa' s.license = 'Public Domain' s.summary = 'A lightweight aggregator of Knowledge Organization Systems (KOS)' s.description = s.summary s.authors = ['uah.es', 'Gregg Kellogg'] s.email = '' s.platform = Gem::Platform::RUBY s.files = %w(README.md) + Dir.glob('lib/**/*.rb') s.bindir = %q(bin) s.executables = %w() s.default_executable = s.executables.first s.require_paths = %w(lib) s.extensions = %w() s.test_files = %w() s.has_rdoc = false s.required_ruby_version = '>= 1.8.7' s.requirements = [] # RDF dependencies s.add_runtime_dependency "linkeddata", '>= 1.0' s.add_runtime_dependency 'equivalent-xml', '>= 0.3.0' s.add_runtime_dependency 'sparql', '>= 1.0' s.add_runtime_dependency 'curb', '>= 0.8.3' # Sinatra dependencies s.add_runtime_dependency 'sinatra', '>= 1.3.3' s.add_runtime_dependency 'erubis', '>= 2.7.0' s.add_runtime_dependency 'haml' s.add_runtime_dependency 'maruku' s.add_runtime_dependency "rack", '>= 1.4.4' s.add_runtime_dependency 'sinatra-respond_to', '>= 0.8.0' s.add_runtime_dependency 'rack-cache' # development dependencies s.add_development_dependency 'yard' s.add_development_dependency 'rspec', '>= 2.12.0' s.add_development_dependency 'rack-test', '>= 0.6.2' s.add_development_dependency 'bundler' s.add_development_dependency 'rdf-do' s.post_install_message = nil end
$:.unshift File.expand_path('../lib/', __FILE__) require 'rake/testtask' require 'rake/clean' # tests : rake test Rake::TestTask.new do |t| t.libs << "test" end # Build the docs : rake docs ronn_files = Rake::FileList['man/*.ronn'] html_docs = ronn_files.ext '.html' man_docs = ronn_files.ext '' ronn_files.each do |doc| # man file out = doc.ext '' file out => doc do sh "ronn --roff #{doc}" end CLEAN << out # html version out = doc.ext 'html' file out => doc do sh "ronn --html --style=toc #{doc}" end CLEAN << out end desc "Build the manpages" task :docs => html_docs + man_docs task :default => :test
class PivotalRequest def self.get_projects_data pivotal_token uri = URI.parse 'https://www.pivotaltracker.com/services/v5/projects' request = Net::HTTP::Get.new uri request['X-Trackertoken'] = pivotal_token get_response request, uri end def self.get_project_stories_data current_user, params url = 'https://www.pivotaltracker.com/services/v5/projects/' \ "#{params[:project_id]}/stories?filter=owner:" \ "#{current_user.pivotal_owner_id}" uri = URI.parse url request = Net::HTTP::Get.new uri request['X-Trackertoken'] = current_user.pivotal_token get_response request, uri end def self.update_story_state current_user, params, request_params = {} url = 'https://www.pivotaltracker.com/services/v5/projects/' \ "#{params[:project_id]}/stories/#{params[:story_id]}" uri = URI.parse url request = Net::HTTP::Put.new uri request['X-Trackertoken'] = current_user.pivotal_token request.content_type = 'application/json' request.body = JSON.dump request_params get_response request, uri end private def self.get_response request, uri req_options = { :use_ssl => uri.scheme == 'https', } response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http| http.request request end response.body end end
Given /^I am on the basic dialog page$/ do visit BasicDialogPage end Then /^the basic dialog title should be "(.+)"$/ do |title| expect(on(BasicDialogPage).the_dialog_title).to eql title end When /^the content should include "(.+)"$/ do |content| expect(on(BasicDialogPage).the_dialog_content).to include content end When /^I close the basic dialog$/ do on(BasicDialogPage).close_the_dialog end Then /^the basic dialog should not be visible$/ do expect(on(BasicDialogPage).the_dialog_element).to_not be_visible end
require 'chefspec' require 'shared' describe 'steamcmd::tf2' do let(:chef_run) { ChefSpec::SoloRunner.converge(described_recipe) } it_behaves_like 'a game recipe' do let(:name) { 'tf2' } let(:id) { 232250 } end describe '/etc/init.d/csgo' do it { expect(chef_run).to render_file('/etc/init.d/tf2').with_content('OPTS="-game tf +map mvm_decoy +ip 0.0.0.0 -port 27016 +maxplayers 32 -pidfile /opt/steamcmd/tmp/tf2.pid"') } it { expect(chef_run).to render_file('/etc/init.d/tf2').with_content('INTERFACE="/usr/bin/screen -A -m -d -S tf2"') } it { expect(chef_run).to render_file('/etc/init.d/tf2').with_content('su - steam -c "cd /opt/steamcmd/apps/tf2 && $INTERFACE /opt/steamcmd/apps/tf2/srcds_run $OPTS"') } it { expect(chef_run).to render_file('/etc/init.d/tf2').with_content('su - steam -c "ps -ef | grep SCREEN | grep tf2 | grep -v grep | awk \'{ print $2 }\' > /opt/steamcmd/tmp/tf2-screen.pid"') } end end
class Location < ApplicationRecord has_many :members # Geocoder # geocoded_by :address, # latitude: :latitude, # longitude: :longitude # after_validation :geocode def self.find_by_si_and_gu(si, gu) where(si: si).where('gu LIKE ?', "%#{gu}%").first end def self.find_by_si(si) where(si: si).first end end
require 'spec_helper' describe ReservationsController do describe "GET 'new'" do describe "when logged in" do it "is successful" do sign_in Factory(:user) get :new response.should be_success end end describe "when not logged in" do before do sign_out :user get :new end it "redirects to the sign in path" do response.should redirect_to(new_user_session_path) end it "has a warning" do flash[:alert].should =~ /need to sign in/i end end end describe "POST 'create'" do describe "success" do before do sign_in Factory(:user) room = Factory(:room) @attr = { name: 'Sample', room_id: room, date: Date.tomorrow, start_time: '12:00 pm', end_time: '2:00 pm'} end it "creates a reservation" do lambda do post :create, reservation: @attr end.should change(Reservation, :count).by(1) end it "redirects to the home page" do post :create, reservation: @attr response.should redirect_to(root_path) end it "has a success message" do post :create, reservation: @attr flash[:success].should =~ /created/i end end describe "failure" do before do sign_in Factory(:user) room = Factory(:room) @attr = { name: 'Sample', date: Date.tomorrow, start_time: '12:00 pm', end_time: '2:00 pm'} end it "does not create a reservation" do lambda do post :create, reservation: @attr end.should_not change(Reservation, :count) end it "renders the new form page" do post :create, reservation: @attr response.should render_template :new end end end describe "GET 'edit'" do describe "when logged in" do describe "as the correct user" do before do @user = Factory(:user) sign_in @user @reservation = Factory(:reservation, user: @user) end it "is successful" do get :edit, id: @reservation response.should be_success end end describe "as the wrong user" do before do @user = Factory(:user) @reservation = Factory(:reservation, user: @user) @other_user = Factory(:user) sign_in @other_user end it "redirects to the home page" do get :edit, id: @reservation response.should redirect_to(root_path) end end end describe "when not logged in" do before do @user = Factory(:user) @reservation = Factory(:reservation, user: @user) sign_out :user end it "is not successful" do get :edit, id: @reservation response.should redirect_to(new_user_session_path) end end end describe "PUT 'update'" do describe "success" do it "updates the reservation" do @user = Factory(:user) sign_in @user @reservation = Factory(:reservation, user: @user) put :update, id: @reservation, reservation: { name: 'New Name' } @reservation.reload @reservation.name.should == 'New Name' end end end describe "DELETE 'destroy'" do it "deletes the record" do @user = Factory(:user) sign_in @user @reservation = Factory(:reservation, user: @user) lambda do delete :destroy, id: @reservation end.should change(Reservation, :count).by(-1) end end end
require 'spec_helper' describe ShareAStatPost do describe 'validations' do subject { FactoryGirl.build(:share_a_stat_post) } it { should be_valid } it { should respond_to(:my_name) } it { should respond_to(:my_number) } it { should respond_to(:friend_1) } it { should respond_to(:friend_2) } it { should respond_to(:friend_3) } it { should respond_to(:friend_4) } it { should respond_to(:friend_5) } it { should respond_to(:friend_6) } describe 'my name' do it 'is required' do subject.my_name = nil expect(subject).to_not be_valid end it 'must be a real name' do subject.my_name = '@#)($*@#$@#$' expect(subject).to_not be_valid end end describe 'my number' do it 'is required' do subject.my_number = nil expect(subject).to_not be_valid end it 'must be a real phone number' do subject.my_number = '@*(#&$)@(#$' expect(subject).to_not be_valid end end describe "my friends' numbers" do it 'are required' do (1..6).each do |n| subject.send("friend_#{n}=", nil) expect(subject).to_not be_valid end end it 'must be real phone numbers' do (1..6).each do |n| subject.send("friend_#{n}=", '@*(#&$)@(#$') expect(subject).to_not be_valid end end end end describe 'Mobile Commons' do before :each do Services::MobileCommons.stub(:subscribe) @sas = FactoryGirl.create(:share_a_stat) @post = FactoryGirl.build(:share_a_stat_post, share_a_stat_id: @sas.id) end after :each do @post.save end it 'sends a text to the alpha' do Services::MobileCommons.should_receive(:subscribe).with(@post.my_number, @sas.mc_alpha) end it 'sends a text to each beta' do (1..6).each do |n| Services::MobileCommons.should_receive(:subscribe).with(@post.send("friend_#{n}"), @sas.mc_beta) end end end end
# This endpoint has a withBreweries option; it should be run after the Brewery # endpoint so that we can link up breweries and beers with fewer API requests. module BreweryDB module Synchronizers class Style < Base protected def fetch(options = {}) @client.get('/styles') end def update!(attributes) style = ::Style.find_or_initialize_by(id: attributes['id']) style.assign_attributes({ name: attributes['name'], category: attributes['category']['name'], description: attributes['description'], min_ibu: attributes['ibuMin'], max_ibu: attributes['ibuMax'], min_abv: attributes['abvMin'], max_abv: attributes['abvMax'], min_original_gravity: attributes['ogMin'], max_original_gravity: attributes['ogMax'], min_final_gravity: attributes['fgMin'], max_final_gravity: attributes['fgMax'], created_at: attributes['createDate'], updated_at: attributes['updateDate'] }) if style.new_record? puts "New style: #{style.name}" end style.save! end end end end
class AddCustomFieldsComputedToken < ActiveRecord::Migration def self.up add_column :custom_fields, :computed_token, :string, {:null => true, :limit => 255} end def self.down remove_column :custom_fields, :computed_token end end
#============================================================================== # ** Game_Pictures #------------------------------------------------------------------------------ # This is a wrapper for a picture array. This class is used within the # Game_Screen class. Map screen pictures and battle screen pictures are # handled separately. #============================================================================== class Game_Pictures end
require 'test_helper' require 'mocha' class MathProblemTest < ActiveSupport::TestCase include MathHotSpotErrors include RightRabbitErrors def setup @math_problem = MathProblem.new @another_problem = MathProblem.new @yet_another_problem = MathProblem.new @three_problems = [@math_problem, @another_problem, @yet_another_problem] @level = @math_problem.build_problem_level @problem_type = @level.build_problem_type end test "group_by_problem_level returns number of groups equal number of levels of existent math problems" do all_levels = MathProblem.all.map { |prob| prob.problem_level } all_levels.uniq! active_levels = all_levels.uniq.reject { |level| level.empty? } groups = MathProblem.group_by_problem_level assert_equal active_levels.size, groups.size end test "replace math problem returns different problem with same problem_type" do third_problem = MathProblem.new MathProblem.expects(:find_all_by_problem_level_id).with(@level.id).returns([@math_problem, @another_problem]) replacement = @math_problem.find_problem_from_same_level assert_equal(@another_problem, replacement) end test "find_problem_from_same_level raises if specified problem's problem_type can not be found" do MathProblem.expects(:find_all_by_problem_level_id).with(@level.id).returns([]) assert_raise ActiveRecord::RecordNotFound do @math_problem.find_problem_from_same_level end end test "find_problem_from_same_level returns problem not being replaced and not exluded" do MathProblem.expects(:find_all_by_problem_level_id).with(@level.id).returns(@three_problems) replacement = @math_problem.find_problem_from_same_level({:exclude => [@another_problem] }) assert_equal @yet_another_problem, replacement end test "find_problem_from_same_level raises if problem is one of a kind" do MathProblem.expects(:find_all_by_problem_level_id).with(@level.id).returns([@math_problem]) assert_raise UniqueProblemError do @math_problem.find_problem_from_same_level end end test "find_problem_from_same_level raises if all available problems excluded" do MathProblem.expects(:find_all_by_problem_level_id).with(@level.id).returns([@math_problem, @another_problem]) assert_raise NoSimilarProblemsRemainingError do @math_problem.find_problem_from_same_level({:exclude => [@another_problem]}) end end test "display_mode? returns true (default) if no problem_level defined" do assert MathProblem.new.display_mode? end test "strip_excess_tags" do input_from_math_type = "<math display='block'><semantics><mrow> <msqrt><mrow><msup><mi>a</mi> <mn>2</mn></msup> <mo>+</mo><msup><mi>b</mi><mn>2</mn></msup></mrow></msqrt><mo>+</mo><mtext>&#x200B;</mtext><mfrac><mrow><mi>n</mi><mo>!</mo></mrow><mrow><mi>r</mi><mo>!</mo><mrow><mo>(</mo><mrow><mi>n</mi><mo>&#x2212;</mo><mi>r</mi></mrow><mo>)</mo></mrow><mo>!</mo></mrow></mfrac></mrow><annotation encoding='MathType-MTEF'> MathType@MTEF@5@5@+=faaagaart1ev2aaaKnaaaaWenf2ys9wBH5garuavP1wzZbqedmvETj2BSbqefm0B1jxALjharqqtubsr4rNCHbGeaGqiVu0Je9sqqrpepC0xbbL8FesqqrFfpeea0xe9Lq=Jc9vqaqpepm0xbba9pwe9Q8fs0=yqaqpepae9pg0FirpepeKkFr0xfr=xfr=xb9Gqpi0dc9adbaqaaeGaciGaaiaabeqaamaabaabaaGcbaWaaOaaaeaacaWGHbWaaWbaaSqabeaacaaIYaaaaOGaey4kaSIaamOyamaaCaaaleqabaGaaGOmaaaaaeqaaOGaey4kaSIaaGzaVpaalaaabaGaamOBaiaacgcaaeaacaWGYbGaaiyiamaabmaabaGaamOBaiabgkHiTiaadkhaaiaawIcacaGLPaaacaGGHaaaaaaa@3D6C@</annotation></semantics></math>" all_striped_down = "<math display='block'><mrow><msqrt><mrow><msup><mi>a</mi><mn>2</mn></msup><mo>+</mo><msup><mi>b</mi><mn>2</mn></msup></mrow></msqrt><mo>+</mo><mtext>&#x200B;</mtext><mfrac><mrow><mi>n</mi><mo>!</mo></mrow><mrow><mi>r</mi><mo>!</mo><mrow><mo>(</mo><mrow><mi>n</mi><mo>&#x2212;</mo><mi>r</mi></mrow><mo>)</mo></mrow><mo>!</mo></mrow></mfrac></mrow></math>" problem = MathProblem.new(:question_markup => input_from_math_type, :answer_markup => 'some answer markup') problem.send(:strip_excess_tags) assert_equal all_striped_down, problem.question_markup end test "removes mathml xmlns and adds display=block for question markup" do input_from_math_type = "<math xmlns='http://www.w3.org/1998/Math/MathML'><mrow><msqrt><mrow><msup><mi>a</mi><mn>2</mn></msup><mo>+</mo><msup><mi>b</mi><mn>2</mn></msup></mrow></msqrt><mo>+</mo><mtext>&#x200B;</mtext><mfrac><mrow><mi>n</mi><mo>!</mo></mrow><mrow><mi>r</mi><mo>!</mo><mrow><mo>(</mo><mrow><mi>n</mi><mo>&#x2212;</mo><mi>r</mi></mrow><mo>)</mo></mrow><mo>!</mo></mrow></mfrac></mrow></math>" all_striped_down = "<math display='block'><mrow><msqrt><mrow><msup><mi>a</mi><mn>2</mn></msup><mo>+</mo><msup><mi>b</mi><mn>2</mn></msup></mrow></msqrt><mo>+</mo><mtext>&#x200B;</mtext><mfrac><mrow><mi>n</mi><mo>!</mo></mrow><mrow><mi>r</mi><mo>!</mo><mrow><mo>(</mo><mrow><mi>n</mi><mo>&#x2212;</mo><mi>r</mi></mrow><mo>)</mo></mrow><mo>!</mo></mrow></mfrac></mrow></math>" problem = MathProblem.new(:question_markup => input_from_math_type, :answer_markup => input_from_math_type) problem.send(:replace_xmlns_with_display_block) assert_equal all_striped_down, problem.question_markup end test "removes mathml xmlns from answer_markup and adds display=block" do input_from_math_type = "<math xmlns='http://www.w3.org/1998/Math/MathML'><mrow><msqrt><mrow><msup><mi>a</mi><mn>2</mn></msup><mo>+</mo><msup><mi>b</mi><mn>2</mn></msup></mrow></msqrt><mo>+</mo><mtext>&#x200B;</mtext><mfrac><mrow><mi>n</mi><mo>!</mo></mrow><mrow><mi>r</mi><mo>!</mo><mrow><mo>(</mo><mrow><mi>n</mi><mo>&#x2212;</mo><mi>r</mi></mrow><mo>)</mo></mrow><mo>!</mo></mrow></mfrac></mrow></math>" all_striped_down = "<math display='block'><mrow><msqrt><mrow><msup><mi>a</mi><mn>2</mn></msup><mo>+</mo><msup><mi>b</mi><mn>2</mn></msup></mrow></msqrt><mo>+</mo><mtext>&#x200B;</mtext><mfrac><mrow><mi>n</mi><mo>!</mo></mrow><mrow><mi>r</mi><mo>!</mo><mrow><mo>(</mo><mrow><mi>n</mi><mo>&#x2212;</mo><mi>r</mi></mrow><mo>)</mo></mrow><mo>!</mo></mrow></mfrac></mrow></math>" problem = MathProblem.new(:question_markup => "some question stuff here", :answer_markup => input_from_math_type) problem.send(:replace_xmlns_with_display_block) assert_equal all_striped_down, problem.answer_markup end test "strip_excess_tags removes newlines from question markup" do input_from_math_type = "<math display='block'> <semantics> <mrow> <mfrac> <mi>x</mi> <mn>2</mn> </mfrac> </mrow> <annotation encoding='MathType-MTEF'> MathType@MTEF@5@5@+=faaagaart1ev2aaaKnaaaaWenf2ys9wBH5garuavP1wzZbqedmvETj2BSbqefm0B1jxALjharqqtubsr4rNCHbGeaGqiVu0Je9sqqrpepC0xbbL8FesqqrFfpeea0xe9Lq=Jc9vqaqpepm0xbba9pwe9Q8fs0=yqaqpepae9pg0FirpepeKkFr0xfr=xfr=xb9Gqpi0dc9adbaqaaeGaciGaaiaabeqaamaabaabaaGcbaWaaSaaaeaacaWG4baabaGaaGOmaaaaaaa@2FDB@</annotation> </semantics> </math> " all_striped_down = "<math display='block'><mrow><mfrac><mi>x</mi><mn>2</mn></mfrac></mrow></math>" problem = MathProblem.new(:question_markup => input_from_math_type, :answer_markup => 'some answer markup') problem.send(:strip_excess_tags) assert_equal all_striped_down, problem.question_markup end test "strip_excess_tags removes newlines from answer markup" do input_from_math_type = "<math display='block'> <semantics> <mrow> <mfrac> <mi>x</mi> <mn>2</mn> </mfrac> </mrow> <annotation encoding='MathType-MTEF'> MathType@MTEF@5@5@+=faaagaart1ev2aaaKnaaaaWenf2ys9wBH5garuavP1wzZbqedmvETj2BSbqefm0B1jxALjharqqtubsr4rNCHbGeaGqiVu0Je9sqqrpepC0xbbL8FesqqrFfpeea0xe9Lq=Jc9vqaqpepm0xbba9pwe9Q8fs0=yqaqpepae9pg0FirpepeKkFr0xfr=xfr=xb9Gqpi0dc9adbaqaaeGaciGaaiaabeqaamaabaabaaGcbaWaaSaaaeaacaWG4baabaGaaGOmaaaaaaa@2FDB@</annotation> </semantics> </math> " all_striped_down = "<math display='block'><mrow><mfrac><mi>x</mi><mn>2</mn></mfrac></mrow></math>" problem = MathProblem.new(:question_markup => "some question markup", :answer_markup => input_from_math_type) problem.send(:strip_excess_tags) assert_equal all_striped_down, problem.answer_markup end test "strip_excess_tags and replace_xmlns_with_display_block don't choke if answer_markup is nil" do problem = MathProblem.new(:question_markup => "some question markup") assert_nothing_raised do problem.send(:strip_excess_tags) problem.send(:replace_xmlns_with_display_block) end end test "instruction when problem_level is nil returns default message" do assert_equal MathProblem::DEFAULT_INSTRUCTION, MathProblem.new.instruction end test "instruction_description returns expected text from level" do expected_msg = "this is the expected message" instruction = Instruction.new(:description => expected_msg) prob = MathProblem.new level = prob.build_problem_level level.expects(:instruction).returns(instruction) assert_equal expected_msg, prob.instruction_description end test "siblings with no params returns all siblings" do problem_level = ProblemLevel.new 4.times {problem_level.math_problems.build} problem = problem_level.math_problems.build problem.problem_level = problem_level expected_siblings = problem_level.math_problems[0..3] assert_equal problem_level, problem.problem_level, "Looks as through level wasn't set" assert_equal expected_siblings, problem.siblings end test "siblings 3 returns only 3 siblings" do problem_level = ProblemLevel.new 4.times {problem_level.math_problems.build} problem = problem_level.math_problems.build problem.problem_level = problem_level assert_equal 3, problem.siblings(3).count end test "math problem is valid without if problem_level nil" do problem = MathProblem.new(:question_markup => 'some markup', :answer_markup => 'some more markup', :owner => User.first) assert problem.valid? end test "math problem invalid if problem_level_id specified but not in db" do level_id = 666 ProblemLevel.expects(:exists?).with(level_id).returns(false) problem = Factory.build(:math_problem, :problem_level_id => level_id) assert_equal false, problem.valid? end test "math problem is invalid without owner" do problem = MathProblem.new(:question_markup => 'some markup', :answer_markup => 'some more markup', :problem_level => problem_levels(:dividing_monomials_level_01)) assert_equal false, problem.valid? end test "sibling_available? returns true with one sibling found and no restrictions" do level_id = 987 @level.stubs(:id).returns(level_id) MathProblem.expects(:find_all_by_problem_level_id).with(level_id).returns(@three_problems) assert @math_problem.sibling_available? end test "sibling_available returns true if one option left" do level_id = 987 @level.stubs(:id).returns(level_id) MathProblem.expects(:find_all_by_problem_level_id).with(level_id).returns(@three_problems) assert @math_problem.sibling_available?(:exclude => [@another_problem]) end test "sibling_available returns false if all options are excluded" do level_id = 987 @level.stubs(:id).returns(level_id) MathProblem.expects(:find_all_by_problem_level_id).with(level_id).returns(@three_problems) assert_equal false, @math_problem.sibling_available?(:exclude => [@another_problem, @yet_another_problem]) end test "math problems with specified problem levels are considered classified" do assert @math_problem.classified?, "Math Problem should be classified because problem_level is specified" end test "math problem with no problem_level are NOT classified" do problem = Factory.build(:math_problem, :problem_level_id => nil) assert_equal false, problem.classified? end private def stub_math_problem_order_to_return_sorted_list(ordered_problem_list) MathProblem.stubs(:grouped_problems).returns(ordered_problem_list) end end
class Instructor attr_reader :name @@all = [] def initialize(name) @name = name @@all << self end def self.all @@all end def pass_student(student, test_name) found = BoatingTest.all.find do |boating_instance| (boating_instance.student == student) && (BoatingTest.test_name == test_name) end if (found) found.test_status = "passed" return found end 0 end def fail_student(student, test_name) found = BoatingTest.all.find do |boating_instance| (boating_instance.student == student) && (BoatingTest.test_name == test_name) end if (found) found.test_status = "failed" return found end 0 end end
include AuthorizeNet::API def transaction transaction = Transaction.new(@api_login_id, @api_transaction_key, @gateway) end def create_customer_token if transaction_ready request = CreateCustomerProfileRequest.new request.profile = CustomerProfileType.new(@customer,@name_full,nil,nil,nil) #(merchantCustomerId,description,email,paymentProfiles,shipToList) @authorize_response = transaction.create_customer_profile(request) # The transaction has a response. if transaction_ok @has_customer_token = true @customer_token = @authorize_response.customerProfileId @status_code = 200 @status_message = "[OK] CustomerTokenCreated" @return_json_package = JSON.generate ["result"=>@result,"status_code"=>@status_code,"status_message"=>@status_message,"customer_token"=>@customer_token][0] elsif @result == "ERROR" @status_code = 199 # Most likely caused by a '@customer' id issue. @status_message = "[ERROR] CustomerTokenNotCreated" @return_json_package = JSON.generate ["result"=>@result,"status_code"=>@status_code,"status_message"=>@status_message,"authorize_response_code"=>@authorize_response_code,"authorize_response_message"=>@authorize_response_message][0] end log_result_to_console end end def create_payment_token if transaction_ready request = CreateCustomerPaymentProfileRequest.new creditcard = CreditCardType.new(@card_number,@card_mmyy,@card_cvv) payment = PaymentType.new(creditcard) # Build an address object billTo = CustomerAddressType.new billTo.firstName = @card_name_first billTo.lastName = @card_name_last billTo.address = @address billTo.city = @city billTo.state = @state billTo.zip = @zip billTo.phoneNumber = @phone # Use the previously defined payment and billTo objects to # build a payment profile to send with the request paymentProfile = CustomerPaymentProfileType.new paymentProfile.payment = payment paymentProfile.billTo = billTo paymentProfile.defaultPaymentProfile = true # Build the request object request.paymentProfile = paymentProfile request.customerProfileId = @customer_token @authorize_response = transaction.create_customer_payment_profile(request) # The transaction has a response. if transaction_ok @payment_token = @authorize_response.customerPaymentProfileId @has_payment_token = true @status_code = 200 @status_message = "[OK] PaymentTokenCreated" @maskedCardNumber = @card_number.split(//).last(4).join @return_json_package = JSON.generate ["result"=>@result,"status_code"=>@status_code,"status_message"=>@status_message,"payment_token"=>@payment_token,"card_number"=>@maskedCardNumber][0] elsif @result == "ERROR" @status_code = 196 @status_message = "[ERROR] PaymentTokenNotCreated" @return_json_package = JSON.generate ["result"=>@result,"status_code"=>@status_code,"status_message"=>@status_message,"authorize_response_code"=>@authorize_response_message,"authorize_response_message"=>@authorize_response_message][0] end log_result_to_console end end def update_payment_token if transaction_ready request = UpdateCustomerPaymentProfileRequest.new # Set the @card_mmyy = 'XXXX' and @card_cvv = nil if the user didn't enter any values. mask_card_date nil_card_cvv # The credit card number should not be updated per Ashley's decision. Hence the use of the @masked_card_number variable. creditcard = CreditCardType.new(@masked_card_number,@card_mmyy,@card_cvv) payment = PaymentType.new(creditcard) profile = CustomerPaymentProfileExType.new(nil,nil,payment,nil,nil) if @update_card_address == true profile.billTo = CustomerAddressType.new profile.billTo.firstName = @name_first profile.billTo.lastName = @name_last profile.billTo.address = @address profile.billTo.city = @city profile.billTo.state = @state profile.billTo.zip = @zip end request.paymentProfile = profile request.customerProfileId = @customer_token profile.customerPaymentProfileId = @payment_token # PASS the transaction request and CAPTURE the transaction response. @authorize_response = transaction.update_customer_payment_profile(request) if transaction_ok @payment_token_updated = true @status_code = 200 @status_message = "[OK] PaymentTokenUpdated" elsif @result == "ERROR" @payment_token_updated = false @status_code = 210 @status_message = "[ERROR] PaymentTokenNotUpdated" @return_json_package = JSON.generate ["result"=>@result,"status_code"=>@status_code,"status_message"=>@status_message,"authorize_response_code"=>@authorize_response_message,"authorize_response_message"=>@authorize_response_message][0] end log_result_to_console end end def delete_payment_token if transaction_ready request = DeleteCustomerPaymentProfileRequest.new request.customerProfileId = @customer_token request.customerPaymentProfileId = @payment_token @authorize_response = transaction.delete_customer_payment_profile(request) # The transaction has a response. if transaction_ok @status_code = 200 @status_message = "[OK] PaymentTokenDeleted" elsif @result == "ERROR" @status_code = 194 @status_message = "[ERROR] PaymentTokenNotDeleted" @return_json_package = JSON.generate ["result"=>@result,"status_code"=>@status_code,"status_message"=>@status_message,"authorize_response_code"=>@authorize_response_message,"authorize_response_message"=>@authorize_response_message][0] end log_result_to_console end end def validate_customer_token if transaction_ready request = GetCustomerProfileRequest.new if @check_by_merchant_id == true request.merchantCustomerId = @customer elsif @check_by_customer_token == true request.customerProfileId = @customer_token end @authorize_response = transaction.get_customer_profile(request) if transaction_ok # This is the expected result when a webapp requests to create a PT. @customer_token = @authorize_response.profile.customerProfileId @has_customer_token = true @status_code = 200 @status_message = "[OK] CustomerTokenExists" elsif @result == "ERROR" # This is the expected result when a webapp requests to create a CT. @has_customer_token = false @status_code = 194 @status_message = "[ERROR] CustomerTokenDoesNotExist" @return_json_package = JSON.generate ["result"=>@result,"status_code"=>@status_code,"status_message"=>@status_message,"authorize_response_code"=>@authorize_response_message,"authorize_response_message"=>@authorize_response_message][0] end log_result_to_console end end def retrieve_payment_token if transaction_ready request = GetCustomerPaymentProfileRequest.new request.customerProfileId = @customer_token request.customerPaymentProfileId = @payment_token @authorize_response = transaction.get_customer_payment_profile(request) if transaction_ok @payment_token_retrieved = true @masked_card_number = @authorize_response.paymentProfile.payment.creditCard.cardNumber elsif @result == "ERROR" @payment_token_retrieved = false @status_code = 240 @status_message = "[ERROR] PaymentTokenCouldNotBeRetrieved" @return_json_package = JSON.generate ["result"=>@result,"status_code"=>@status_code,"status_message"=>@status_message,"authorize_response_code"=>@authorize_response_message,"authorize_response_message"=>@authorize_response_message][0] end log_result_to_console end end def validate_tokens if transaction_ready request = ValidateCustomerPaymentProfileRequest.new #Edit this part to select a specific customer request.customerProfileId = @customer_token request.customerPaymentProfileId = @payment_token request.validationMode = ValidationModeEnum::TestMode # PASS the transaction request and CAPTURE the transaction response. @authorize_response = transaction.validate_customer_payment_profile(request) if transaction_ok @valid_tokens = true elsif @result == "ERROR" @valid_tokens = false @authorize_response_kind = "TokenError" log_result_to_console end end end # This method connects all of the payment processing methods together. def process_payment if transaction_ready request = CreateTransactionRequest.new request.transactionRequest = TransactionRequestType.new() request.transactionRequest.amount = @amount request.transactionRequest.transactionType = TransactionTypeEnum::AuthCaptureTransaction if @card_or_tokens == "tokens" request.transactionRequest.profile = CustomerProfilePaymentType.new request.transactionRequest.profile.customerProfileId = @customer_token request.transactionRequest.profile.paymentProfile = PaymentProfile.new(@payment_token) elsif @card_or_tokens == "card" request.transactionRequest.payment = PaymentType.new request.transactionRequest.payment.creditCard = CreditCardType.new(@card_number, @card_mmyy, @card_cvv) end # The @gl_code and @invoice were set dynamically in the set_gl_code method located in the shared.rb file. request.transactionRequest.order = OrderType.new() request.transactionRequest.order.invoiceNumber = @invoice request.transactionRequest.order.description = @gl_code # PASS the transaction request and CAPTURE the transaction response. @authorize_response = transaction.create_transaction(request) # The transaction has a response. if transaction_ok # Capture the response variables for all transactions. @avs_code = @authorize_response.transactionResponse.avsResultCode @cvv_code = @authorize_response.transactionResponse.cvvResultCode # CAPTURE the transaction details. @transaction_id = @authorize_response.transactionResponse.transId @transaction_response_code = @authorize_response.transactionResponse.responseCode if @transaction_response_code == "1" @authorize_response_kind = "Approved" @authorization_code = @authorize_response.transactionResponse.authCode transaction_payment_ok else if @transaction_response_code == "2" @authorize_response_kind = "Declined" elsif @transaction_response_code == "3" @authorize_response_kind = "Error" elsif @transaction_response_code == "4" @authorize_response_kind = "HeldforReview" end transaction_payment_error end # A transactional ERROR occurred. elsif @result == "ERROR" @authorize_response_kind = "TransactionError" transaction_payment_error end end end
class AddColAdminToRestaurants < ActiveRecord::Migration def change add_column :restaurants, :admin_id, :integer end end
require 'gaman/logging' require 'gaman/fibs' require 'gaman/terminal/prompt' require 'gaman/terminal/status' require 'gaman/terminal/command' require 'gaman/terminal/screen' require 'gaman/terminal/user_interface' require 'gaman/terminal/view/login' require 'gaman/terminal/view/welcome' require 'gaman/terminal/view/messaging' require 'gaman/terminal/view/players' # Main controller for the terminal client for FIBS (`gaman`). Co-ordinates # main flow of the application and connection with FIBS -- hands display off # to the View helper classes and the UI class (using Curses). class Gaman::Terminal::Controller include Gaman::Logging include Gaman::Terminal # rubocop:disable all def run UserInterface.use do |ui| # these are inactive by default login_view = View::Login.new(ui) welcome_view = View::Welcome.new(ui) messaging_view = View::Messaging.new(ui) players_view = View::Players.new(ui) logger.debug { 'activating login view' } login_view.activate logger.debug { 'getting next action from login view' } cmd = login_view.next_action break if cmd == Command::QUIT username, password = login_view.credentials if cmd == Command::LOGIN login_view.deactivate ui.status Status::ATTEMPTING_CONNECTION # TODO: throw exceptions when not connected and fibs is used. Gaman::Fibs.use(username: username, password: password) do |fibs| logger.debug { 'registering listeners' } fibs.register_listener(messaging_view, :messages) # fibs.register_listener(players_view, :players) logger.debug { 'starting views' } view = welcome_view view.activate loop do new_view = case view.next_action when action.quit? then nil when action.main? then welcome_view when action.messaging? then messaging_view when action.players_list? then players_view end view.deactivate view = new_view view.activate end end end end end
class UserMailer < Devise::Mailer helper :application # gives access to all helpers defined within `application_helper`. include Devise::Controllers::UrlHelpers # Optional. eg. `confirmation_url` default template_path: 'devise/mailer' # to make sure that your mailer uses the devise views def confirmation_instructions(record, token, opts={}) @token = token @resource = record @resource = record require 'mailgun' mg_client = Mailgun::Client.new "key-a2ba6d81aa1687b45c6ea03b82221013" html = render_to_string template: "devise/mailer/confirmation_instructions.html.erb" # Define your message parameters message_params = {:from => 'Articity <contact@articity.in>', :to => record.email, :subject => 'Welcome to Articity!', :html => html.to_str} # Send your message through the client mg_client.send_message "mail.articity.in", message_params end def reset_password_instructions(record, token, opts={}) @token = token @resource = record require 'mailgun' mg_client = Mailgun::Client.new "key-a2ba6d81aa1687b45c6ea03b82221013" html = render_to_string template: "devise/mailer/reset_password_instructions.html.erb" # Define your message parameters message_params = {:from => 'Articity <contact@articity.in>', :to => record.email, :subject => 'Password reset request', :html => html.to_str} # Send your message through the client mg_client.send_message "mail.articity.in", message_params # code to be added here later end def password_change(record, opts={}) @resource = record require 'mailgun' mg_client = Mailgun::Client.new "key-a2ba6d81aa1687b45c6ea03b82221013" html = render_to_string template: "devise/mailer/password_change.html.erb" # Define your message parameters message_params = {:from => 'Articity <contact@articity.in>', :to => record.email, :subject => 'You have changed your password', :html => html.to_str} # Send your message through the client mg_client.send_message "mail.articity.in", message_params end end
module RailsAdmin module Config module Actions class MultiDeactiveQuestion < RailsAdmin::Config::Actions::Base RailsAdmin::Config::Actions.register(self) register_instance_option :collection do true end register_instance_option :http_methods do [:post, :patch] end register_instance_option :controller do proc do if request.post? if params[:cancel] redirect_to back_or_index, alert: flash_message("questions_cancel") else @active_questions = list_entries(@model_config) render @action.template_name end elsif request.patch? @questions = Question.where id: params[:bulk_ids] @questions.update_all active: 0 redirect_to back_or_index, notice: flash_message("multi_deactive_question") end end end register_instance_option :authorization_key do :destroy end register_instance_option :bulkable? do true end end end end end
# Copyright 2015 ClearStory Data, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. if platform_family?('rhel') && node['monit']['install_method'] != 'source' Chef::Log.warn( "Setting node['monit']['install_method'] to 'source' on a RedHat-based system because " \ "the monit_wrapper cookbook requires a Monit version of 5.2 or later to utilize the " \ "'matching' feature. Please note that this won't help if the monit-ng default recipe " \ "is included in the run list before the monit_wrapper recipe." ) node.override['monit']['install_method'] = 'source' node.default['monit']['executable'] = '/usr/local/bin/monit' else node.default['monit']['executable'] = '/usr/bin/monit' end include_recipe 'monit-ng' # Ensure monit daemon is running. This may not happen on its own on Docker. We are not using the # "service" resource, because service[monit] is also defined in monit-ng, and we do not want to # interfere with that resource's execution here. ruby_block 'monit_wrapper_start_monit_service' do block { ensure_monit_daemon_is_running } end chef_gem 'waitutil' template '/usr/local/bin/start_stop_service_from_monit.sh' do source 'start_stop_service_from_monit.sh.erb' owner 'root' group 'root' mode '0744' variables timeout_sec: node['monit_wrapper']['start_stop_timeout_sec'] end template '/usr/local/bin/monit_service_ctl.sh' do source 'monit_service_ctl.sh.erb' owner 'root' group 'root' mode '0755' variables monit_executable: node['monit']['executable'] end # We use this directory for lock files to ensure that no more than one process is trying to # start/stop a particular service from start_stop_service_from_monit.sh at any given moment. directory '/var/monit' do owner' root' group 'root' mode '0777' end
module CharacterReorderTest def reorder(factory_name, class_name, list_of_modules) test 'Reorder Items' do skip "TODO -> figure out how fix drag and drop" create_n_objects(3, factory_name) position_0_before = class_name.find(@instances_of_class[0].id)._position position_1 = class_name.find(@instances_of_class[1].id)._position position_2 = class_name.find(@instances_of_class[2].id)._position visit('/admin') wait_for_ajax # Select Module select_last_module_from_list(list_of_modules) drag_item(@instances_of_class[0], @instances_of_class[1]) position_0_after = class_name.find(@instances_of_class[0].id)._position title_2 = find("a[data-id='#{@instances_of_class[0].id}']+a").text title_0 = find("a[data-id='#{@instances_of_class[1].id}']+a").text assert page.has_css?('div.item-title', text: @instances_of_class[0].title, count: 1) assert_not_equal position_0_before, position_0_after assert position_0_after > position_1 && position_0_after < position_2 assert_equal @instances_of_class[0].title, title_0 assert_equal @instances_of_class[2].title, title_2 end end def reorder_to_begin_of_list(factory_name, class_name, list_of_modules) test 'Reorder Item in Begining of List' do skip "TODO -> figure out how fix drag and drop" create_per_page_plus_n_objects(2, factory_name) visit('/admin') wait_for_ajax select_last_module_from_list(list_of_modules) wait_for_ajax sleep(1.0) assert page.has_css?('div.item-title', count: @loaded_items) scroll_to_bottom wait_for_ajax scroll_to_bottom drag_item(@last_item, @first_item) title_second_item = find("a[data-id='#{@last_item.id}']+a").text assert page.has_css?('div.item-title', count: class_name.count) assert_equal @first_item.title, title_second_item end end end
class ActivitiesController < ApplicationController before_action :find_activity, only: [:show] def index @activities = Activity.all end def show end protected def find_activity @activity = Activity.find_by(permalink: params[:id]) if @activity.nil? && activity = Activity.find(params[:id]) redirect_to activity_path(activity) return false end end end
# encoding: UTF-8 module OmniSearch ## # Sets the location of # file storage # classes which define indexes # # Usage # --------------------------------- # OmniSearch.configuration {|config| # config.path_to_index_files = '/tmp/omnisearch_sparkle/' # config.path_to_autoload_search_classes_from = # File.join(Rails.root, '/app/search_indexes') # } # class Configuration # we need to store indexes somewhere attr_accessor :path_to_index_files # due to autoloading, we need to explicitly require our # search classes from somewhere, this is where we will look attr_accessor :path_to_autoload_search_classes_from # currently there are two types of indicies # trigram and plain # you may add another index type by adding it to this array attr_accessor :index_types # memcache server: # in the format serveraddress:port # the default for memcache is localhost:11211 attr_accessor :memcache_server # memcache namespace: # omnisearch not use the global memcache namespace attr_accessor :memcache_namespace #seach_strategy: # the class to call '.run on, with a query' attr_accessor :search_strategy DEFAULTS = { path_to_index_files: '/tmp/omnisearch/', path_to_autoload_search_classes_from: nil, index_types: [ Indexes::Plaintext, Indexes::Trigram ], search_strategy: OmniSearch::Search::Strategy, memcache_server: 'localhost:11211', memcache_namespace: 'omnisearch' } def initialize(options={}) DEFAULTS.each do |key, value| self.send("#{key}=", options[key] || value) end end end # inject the attr_accessor into the class/module, yah. def self.configuration @configuration ||= Configuration.new end def self.configure self.configuration ||= Configuration.new yield(configuration) end end
module DeviseHelper def devise_error_messages! return '' unless devise_error_messages? html_error_explanation end def devise_error_messages? !resource.errors.empty? end private def html_error_explanation html = <<-HTML <div id="error_explanation" class="alert alert-danger"> <p class="margin-0"><strong>#{sentence}</strong></p> <ul>#{messages}</ul> </div> HTML html.html_safe end def sentence I18n.t('errors.messages.not_saved', count: resource.errors.count, resource: resource.class.model_name.human.downcase) end def messages resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join end end
class AddRecipeIngredientToItems < ActiveRecord::Migration[5.0] def change add_column :items, :recipe_ingredient, :string end end
# Methods added to this helper will be available to all templates in the application. module ApplicationHelper def generate_heads(array) reply = "<thead>\n<tr>\n" array.each do |s| reply += "<th>#{s}</th>\n" end reply += "</tr>\n</thead>\n" reply end end
module TestCollection # Anything that includes TestCollection must, during setup, assign @subject and @factory, where # @subject is the collection under test, (e.g. Fog::Compute[:google].servers) # @factory is a CollectionFactory def test_lifecycle one = @subject.new(@factory.params) one.save two = @subject.create(@factory.params) # XXX HACK compares identities # should be replaced with simple includes? when `==` is properly implemented in fog-core; see fog/fog-core#148 assert_includes @subject.all.map(&:identity), one.identity assert_includes @subject.all.map(&:identity), two.identity assert_equal one.identity, @subject.get(one.identity).identity assert_equal two.identity, @subject.get(two.identity).identity # Some factories that have scoped parameters (zone, region) have a special # `get` method defined in the factory to pass the correct parameters in if @factory.respond_to?(:get) assert_equal one.identity, @factory.get(one.identity).identity assert_equal two.identity, @factory.get(two.identity).identity end # Some factories that have scoped parameters (zone, region) have a special # `all` method defined in the factory to pass the correct parameters in if @factory.respond_to?(:all) subject_list = @subject.all scoped_subject_list = @factory.all # Assert that whatever .all(scope) returns is a subset of .all assert(scoped_subject_list.all? { |x| subject_list.include? x }, "Output of @factory.all must be a subset of @subject.all") end one.destroy two.destroy Fog.wait_for { !@subject.all.map(&:identity).include? one.identity } Fog.wait_for { !@subject.all.map(&:identity).include? two.identity } end def test_get_returns_nil_if_resource_does_not_exist assert_nil @factory.get("fog-test-fake-identity") if @factory.respond_to?(:get) assert_nil @subject.get("fog-test-fake-identity") end def test_enumerable assert_respond_to @subject, :each end def test_nil_get assert_nil @subject.get(nil) end def teardown @factory.cleanup end end
class UsersController < ApplicationController before_action :authorized, except: %i[create request_token show] def create @user = User.create(user_params) if @user.valid? token = encode_token({ user_id: @user.id }) render json: { user: @user, token: token } else render json: { error: 'Invalid email or password' } end end def request_token @user = User.find_by(email: params[:email]) if @user&.api_key == params[:api_key] token = encode_token({ user_id: @user.id }) render json: token else render json: { error: 'Invalid email or API key' } end end def show redirect_to :new_user_session unless user_signed_in? end private def user_params params.permit(:email, :api_key) end end
require 'spec_helper' describe ExamRoom::Practice::Emq do before :each do setup_for_models @practice_exam = TestSupport::ExamRoom.generate_practice_emq_exam! @practice_question = ExamRoom::Practice::Question.find(@practice_exam.questions.first.id) @question = @practice_question.question @attempt_hash = @question.stems.inject({}) do |hash, stem| hash[stem.id] = stem.answer_id hash end end describe "when attempted" do it "it should remember that it has been attempted" do @practice_question.attempt!(@attempt_hash) @practice_question.attempted.should == true end it "should record it's finish time when attempted" do @practice_question.finished_at.should be_nil @practice_question.attempt!(@attempt_hash) @practice_question.finished_at.to_f.should be_within(1).of DateTime.now.to_f end it "it should save stems and answers" do @practice_question.attempt!(@attempt_hash) @practice_question.stems.count.should == @question.stems.count end it "should correctly calculate the score and percentage" do user = TestSupport::General.create_user! [ [[true, false, true, false, nil], [2,2,1]], [[true, false, false, false, nil], [1,3,1]] ].each do |permutation| question = ExamRoom::Emq.new(:question => "Question") (0..4).each do |index| answer = question.answers.build(:content => "I am answer #{index + 1}") question.stems.build(:content => "I am stem #{index + 1}", :answer => answer) end question.save! exam = TestSupport::ExamRoom.create_exam! practice_exam = ExamRoom::Practice::Exam.create!(:exam => exam, :num_questions => 1, :user => user) practice_question = ExamRoom::Practice::Emq.create!(:question => question, :number => 1, :practice_exam => practice_exam) attempt_hash = {} permutation[0].each_with_index do |attempt, index| unless attempt === nil stem = question.stems[index] attempt_hash[stem.id] = attempt ? stem.answer_id : question.answers.where("id != ?", stem.answer.id).first.id end end practice_question.attempt!(attempt_hash) practice_question.stems.count.should == permutation[0].length practice_question.stems.where(["correct = ?", true]).count.should == permutation[1][0] practice_question.stems.where(["correct = ?", false]).count.should == permutation[1][1] practice_question.stems.where("correct IS NULL").count.should == permutation[1][2] practice_question.score.should == permutation[1][0] practice_question.num_correct_answers.should == permutation[1][0] practice_question.num_incorrect_answers.should == permutation[1][1] practice_question.num_skipped_answers.should == permutation[1][2] end end end end
FactoryGirl.define do factory :person do name { Faker::Name.name } lastname { Faker::Name.name } phone { Faker::PhoneNumber.phone_number } email { Faker::Internet.email } password "1" password_confirmation "1" end end
# -*- coding: utf-8 -*- require 'spec_helper' class TestRequest < Mushikago::Http::GetRequest include Mushikago::Auth::Signature end describe Mushikago::Http::Client do context 'construct without options' do before :all do @client = Mushikago::Http::Client.new end subject{ @client } its(:api_key){ should == Mushikago.config.api_key.to_s } end context 'construct with options' do before :all do @client = Mushikago::Http::Client.new( :api_key => 'mushikago api key' ) end subject{ @client } its(:api_key){ should == 'mushikago api key' } end context 'send test request' do before :all do request = TestRequest.new request.host = 'api.mushikago.org' request.port = 443 request.path = '/1/health/check' client = Mushikago::Http::Client.new @response = client.send_request(request) end subject{ @response } it{ should respond_to(:meta, :response) } end end
class AddHeaderClickTypeToContacts < ActiveRecord::Migration[6.0] def change add_column :contacts, :header_click_type, :string end end
require 'SVG/Graph/Bar' class GraphActivitiesController < ApplicationController unloadable layout 'base' before_filter :init def init @project = Project.find(params[:id]) @assignables = @project.assignable_users retrieve_date_range end def retrieve_activities @author = (params[:user_id].blank? ? nil : User.active.find(params[:user_id])) @activity = Redmine::Activity::Fetcher.new(User.current, :project => @project, :with_subprojects => Setting.plugin_redmine_graph_activities['include_subproject'], :author => @author ) @activity.scope_select {|t| !params["show_#{t}"].nil?} @activity.scope = (@author.nil? ? :default : :all) if @activity.scope.empty? @events = @activity.events(@from, @to + 1) rescue ActiveRecord::RecordNotFound render_404 end def retrieve_date_range @from, @to = nil, nil if !params[:from].nil? begin @from = params[:from].to_s.to_date unless params[:from].blank? rescue @from = Date.today - 28 end else @from = Date.today - 28 end if !params[:to].nil? begin @to = params[:to].to_s.to_date unless params[:to].blank? rescue @to = Date.today end else @to = Date.today end @from, @to = @to, @from if @from && @to && @from > @to end def view end def graph retrieve_activities data = make_graph headers["Content-Type"] = "image/svg+xml" send_data(data, :type => "image/svg+xml", :disposition => "inline") end def graph_issue_per_day retrieve_activities data = make_graph_issue_per_day headers["Content-Type"] = "image/svg+xml" send_data(data, :type => "image/svg+xml", :disposition => "inline") end def graph_repos_per_day retrieve_activities data = make_graph_repos_per_day headers["Content-Type"] = "image/svg+xml" send_data(data, :type => "image/svg+xml", :disposition => "inline") end private def make_graph act_issues = Array.new(24, 0) act_repos = Array.new(24, 0) field = Array.new(24){|i| i} @events.each do |e| if e.event_type[0..4] == 'issue' act_issues[ e.event_datetime.strftime("%H").to_i ] += 1 elsif e.event_type == 'changeset' act_repos[ e.event_datetime.strftime("%H").to_i ] += 1 end end graph = SVG::Graph::Bar.new({ :height => 400, :width => 960, :fields => field, :stack => :side, :scale_integers => true, :step_x_labels => 1, :x_title => l(:field_hours), :show_x_title => true, :y_title => l(:count), :show_y_title => true, :show_data_values => true, :graph_title => l(:all_activities, :start => format_date(@from), :end => format_date(@to)), :show_graph_title => true }) graph.add_data({ :data => act_issues, :title => l(:act_issue) }) graph.add_data({ :data => act_repos, :title => l(:act_repos) }) graph.burn end def make_graph_issue_per_day act_issues = Array.new 7.times do |i| act_issues.push( Array.new(24, 0) ) end field = Array.new(24){|i| i} @events.each do |e| if e.event_type[0..4] == 'issue' d = e.event_datetime.strftime("%w").to_i t = e.event_datetime.strftime("%H").to_i act_issues[d][t] += 1 end end graph = SVG::Graph::Bar.new({ :height => 400, :width => 960, :fields => field, :stack => :side, :scale_integers => true, :step_x_labels => 1, :x_title => l(:field_hours), :show_x_title => true, :y_title => l(:count), :show_y_title => true, :show_data_values => false, :graph_title => l(:activities_issue_per_day), :show_graph_title => true }) 7.times do |i| graph.add_data({ :data => act_issues[i], :title => day_name(i) }) end graph.burn end def make_graph_repos_per_day act_repos = Array.new 7.times do |i| act_repos.push( Array.new(24, 0) ) end field = Array.new(24){|i| i} @events.each do |e| if e.event_type == 'changeset' d = e.event_datetime.strftime("%w").to_i t = e.event_datetime.strftime("%H").to_i act_repos[d][t] += 1 end end graph = SVG::Graph::Bar.new({ :height => 400, :width => 960, :fields => field, :stack => :side, :scale_integers => true, :step_x_labels => 1, :x_title => l(:field_hours), :show_x_title => true, :y_title => l(:count), :show_y_title => true, :show_data_values => false, :graph_title => l(:activities_repos_per_day), :show_graph_title => true }) 7.times do |i| graph.add_data({ :data => act_repos[i], :title => day_name(i) }) end graph.burn end end
module Annealing class PolyGroup attr_accessor :polys, :color, :fill def initialize(polys) @fill = "#cccccc" @polys = polys end def ==(other) other.polys.sort == self.polys.sort end def eq(other) self.==(other) end def rainbow! self.color = %w{red yellow orange green blue violet}.sample self end def inspect "pg[ #{polys.map(&:inspect).join(', ')} ]" end def triangulate threed = polys.map do |p| td = p.triangulate td.respond_to?(:polys) ? td.polys : td end g = PolyGroup.new(threed.flatten) g.color = self.color g end def slice_x(x) partition = ->(p) { x > p.x } mid_y = ->(p1, p2) do Point.new( x, p1.y + (p2.y - p1.y) * (x - p1.x) / (p2.x - p1.x) ) end slice(partition, mid_y, self.triangulate) end def slice_y(y) partition = ->(p) { y > p.y } mid_x = ->(p1, p2) do Point.new( p1.x + (p2.x - p1.x) * (y - p1.y) / (p2.y - p1.y), y) end slice(partition, mid_x, self.triangulate) end # returns an array of PolyGroups def allocate(n) return [PolyGroup.new([])] if n <= 0 triangles = self.triangulate return [PolyGroup.new(triangles.polys)] if n == 1 t1, t2 = triangles.halve_triangles(n) a1 = t1.area a2 = t2.area f = ((n.to_f * a1) / (a1 + a2)).round alloc1 = t1.allocate(f) alloc2 = t2.allocate(n - f) alloc1 + alloc2 end def halve_triangles(n) l,t,r,b = bounding_rect f = n.to_i h = f / 2 if (r - l) > (b - t) slice_x((r * h + l * (f - h)) / f) else slice_y((b * h + t * (f - h)) / f) end end def area @area ||= polys.inject(0){|s,p| s + p.area } end def center return nil unless polys.any? l,t,r,b = bounding_rect midx = (r+l) / 2.0 midy = (b+t) / 2.0 lh, rh = slice_x(midx) th, bh = PolyGroup.new(lh.polys + rh.polys).slice_y(midy) true_center = Point.new(midx, midy) sort = ->(p0,p1) { p0.distance_to(true_center) <=> p1.distance_to(true_center) } all_points = [lh,rh,th,bh].map(&:polys).flatten.map(&:points).flatten all_points.sort(&sort).first end def bounds @bounds ||= Polygon.make(*convex_hull(polys.flat_map(&:points))) end private # monotone chain def convex_hull(pts) pts = pts.sort.uniq return pts if pts.length < 3 lower = [] pts.each do |p| while lower.length > 1 && !cross?(lower[-2], lower[-1], p) do lower.pop end lower.push(p) end upper = [] pts.reverse_each do |p| while upper.length > 1 && !cross?(upper[-2], upper[-1], p) do upper.pop end upper.push(p) end lower[0...-1] + upper[0...-1] end def cross?(o, a, b) (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x) > 0 end def bounding_rect ps = polys.map(&:points).flatten xs = ps.map(&:x) ys = ps.map(&:y) [xs.min, ys.min, xs.max, ys.max] end def slice(partition, centerpoint, triangles) antipartition = ->(p){ !partition[p] } [ clipping(partition, centerpoint, triangles), clipping(antipartition, centerpoint, triangles) ] end def clipping(partition, centerpoint, triangles) PolyGroup.new(triangles.polys.map do |t| inside, outside = t.points.partition( &partition ) clip_triangles(centerpoint, inside, outside) end.flatten) end def clip_triangles(centerpoint, inside, outside) case inside.length when 0 [] when 1 a, b, c = inside[0], outside[0], outside[1] [Polygon.make( a, centerpoint[a,b], centerpoint[a,c] )] when 2 a, b, c = inside[0], inside[1], outside[0] [Polygon.make( a, centerpoint[a,c], b), Polygon.make(b, centerpoint[a,c], centerpoint[b,c])] when 3 [Polygon.make(*inside)] end end end end
class ClinicAssociate < User belongs_to :clinic end
FactoryBot.define do factory :league_schedulers_weekly, class: League::Schedulers::Weekly do league start_of_week { 'Sunday' } minimum_selected { 3 } days { Array.new(7, true) } end end
class RenameTrainerColumnOnUser < ActiveRecord::Migration[6.0] def change rename_column :users, :trainer?, :trainer end end
$LOAD_PATH << 'lib' require 'trip' Gem::Specification.new do |g| g.name = 'trip.rb' g.homepage = 'https://github.com/rg-3/trip.rb' g.authors = ['rg'] g.email = '1aab@protonmail.com' g.version = Trip::VERSION g.summary = <<-SUMMARY Trip is a concurrent tracer that can pause, resume and alter code while it is being traced. Under the hood, Trip uses `Thread#set_trace_func`. SUMMARY g.description = <<-DESCRIPTION Trip is a concurrent tracer that can pause, resume and alter code while it is being traced. Trip yields control between two threads, typically the main thread and a thread that Trip creates. Under the hood, Trip uses `Thread#set_trace_func` and spawns a new thread dedicated to running and tracing a block of Ruby code. Control is yielded between the main thread and this new thread until the trace completes. DESCRIPTION g.licenses = ['MIT'] g.files = `git ls-files`.split($/) g.required_ruby_version = '>= 2.0' end
class BankAccount < ActiveRecord::Base has_many :offers validates :cc, :bank, :agency, :bank_number, :operation_code, :cnpj_cpf, :owner_name, presence: true end
module OcrMutations class ExtractText < Mutations::BaseMutation argument :id, GraphQL::Types::ID, required: true field :project_media, ProjectMediaType, null: true, camelize: false def resolve(id:) pm = GraphqlCrudOperations.object_from_id_if_can( id, context[:ability] ) Bot::Alegre.get_extracted_text(pm) { project_media: pm } end end end
# frozen_string_literal: true # rubocop:todo all require 'spec_helper' describe Mongo::Auth::Aws::CredentialsCache do require_auth 'aws-ec2', 'aws-ecs', 'aws-web-identity' def new_client ClientRegistry.instance.new_authorized_client.tap do |client| @clients << client end end before do @clients = [] described_class.instance.clear end after do @clients.each(&:close) end it 'caches the credentials' do client1 = new_client client1['test-collection'].find.to_a expect(described_class.instance.credentials).not_to be_nil described_class.instance.credentials = Mongo::Auth::Aws::Credentials.new( described_class.instance.credentials.access_key_id, described_class.instance.credentials.secret_access_key, described_class.instance.credentials.session_token, Time.now + 60 ) client2 = new_client client2['test-collection'].find.to_a expect(described_class.instance.credentials).not_to be_expired described_class.instance.credentials = Mongo::Auth::Aws::Credentials.new( 'bad_access_key_id', described_class.instance.credentials.secret_access_key, described_class.instance.credentials.session_token, described_class.instance.credentials.expiration ) client3 = new_client expect { client3['test-collection'].find.to_a }.to raise_error(Mongo::Auth::Unauthorized) expect(described_class.instance.credentials).to be_nil expect { client3['test-collection'].find.to_a }.not_to raise_error expect(described_class.instance.credentials).not_to be_nil end end
# == Schema Information # # Table name: searches # # id :integer not null, primary key # created_at :datetime not null # updated_at :datetime not null # lat :float not null # long :float not null # radius :integer not null # FactoryGirl.define do factory :search do trait :with_acceptable_values do lat 37.7825447 long -122.4111301 radius 1000 end trait :with_unacceptable_values do lat -91.91 long 181.01 radius 1000 end trait :with_park_city_coords do lat 40.6481408 long -111.570002 radius 5000 end trait :with_too_low_integer do lat 37.7825447 long -122.4111301 radius -1 end trait :with_too_large_integer do lat 37.7825447 long -122.4111301 radius 5001 end trait :with_non_integer do lat 37.7825447 long -122.4111301 radius "brent" end end end
class CreateCommissionMemberships < ActiveRecord::Migration def change create_table :commission_memberships do |t| t.string :position t.integer :commission_id t.integer :member_id t.timestamps end add_index :commission_memberships, :commission_id add_index :commission_memberships, :member_id end end