text
stringlengths
10
2.61M
source 'https://rubygems.org' git_source(:github) { |repo| "https://github.com/#{repo}.git" } ruby '2.6.3' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '~> 6.0.x' # Use postgresql as the database for Active Record gem 'pg', '>= 0.18', '< 2.0' # Use Puma as the app server gem 'puma', '~> 3.11' # Use SCSS for stylesheets gem 'sass-rails', '~> 5' # Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker gem 'webpacker', '~> 4.0' # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.5' # Use Redis adapter to run Action Cable in production gem 'redis', '~> 4.0' # Use Active Model has_secure_password # gem 'bcrypt', '~> 3.1.7' # Use Active Storage variant # gem 'image_processing', '~> 1.2' # Reduces boot times through caching; required in config/boot.rb gem 'bootsnap', '>= 1.4.2', require: false group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug', platforms: %i[mri mingw x64_mingw] end group :development do gem 'capistrano', '~> 3.11' gem 'capistrano-rails', '~> 1.4' gem 'capistrano-faster-assets' gem 'capistrano-passenger', '~> 0.2.0' gem 'capistrano-rbenv', '~> 2.1', '>= 2.1.4' gem 'capistrano-rails-console', require: false gem 'capistrano-rails-logs-tail' gem 'listen', '>= 3.0.5', '< 3.2' gem 'rubocop' # Access an interactive console on exception pages or by calling 'console' anywhere in the code. gem 'web-console', '>= 3.3.0' # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' gem 'spring-watcher-listen', '~> 2.0.0' # irbtools includes interactive_editor gem (vim inside irb)\ # just create ~/.irbrc with\ # require "rubygems"\ # require "irbtools"\ gem 'irbtools', require: 'irbtools/binding' end group :test do # Adds support for Capybara system testing and selenium driver gem 'capybara', '>= 2.15' gem 'selenium-webdriver' gem 'timecop' gem 'vcr' # Easy installation and use of web drivers to run system tests with browsers gem 'webdrivers' gem 'webmock' end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: %i[mingw mswin x64_mingw jruby] # user authentication # https://stackoverflow.com/a/65732099 gem 'devise', github: 'heartcombo/devise', branch: 'ca-omniauth-2' gem 'omniauth-facebook' gem 'omniauth-google-oauth2' # https://stackoverflow.com/a/66155946/287166 gem 'omniauth-rails_csrf_protection' # pick icons by: fontello open; {select icons}; fontello convert gem 'fontello_rails_converter', github: 'railslove/fontello_rails_converter' # bootstrap form # use master untill new release includes https://github.com/bootstrap-ruby/bootstrap_form/pull/550 gem 'bootstrap_form', git: 'https://github.com/bootstrap-ruby/bootstrap_form.git' # translation gem 'mobility', '~> 0.8.6' # money gem 'money-rails', '~> 1.14' # recaptcha for contact form gem 'recaptcha' # error notification to EXCEPTION_RECIPIENTS emails gem 'exception_notification' # open emails in browser gem 'letter_opener' # background job proccessing gem 'sidekiq' # geocoding gem 'geocoder' # enable cors for development gem 'rack-cors' # recurring events gem 'montrose', github: 'rossta/montrose', branch: 'main' # use custom start_number gem 'mustache' gem 'rubyzip', '>=1.3.0' # datatables gem 'trk_datatables', '~>0.2.11' # gem 'trk_datatables', path: '~/gems/trk_datatables' # sortable gem 'acts_as_list' gem 'sitemap_generator', '~>6.1.2' gem 'whenever', require: false gem 'action_policy' # to help in translations gem 'cyrillizer' gem 'google-cloud-translate-v2' # this includes stimulus-rails and turbo-rails gems gem 'hotwire-rails'
class UserAnalyticsPresenter include ApplicationHelper include DashboardHelper include ActionView::Helpers::NumberHelper include Reports::Percentage include BustCache def initialize(current_facility) @current_facility = current_facility.source end attr_reader :current_facility CACHE_VERSION = 5 EXPIRE_STATISTICS_CACHE_IN = 15.minutes def cohort_controlled(cohort) display_percentage(cohort_percentages(cohort)[:controlled]) end def cohort_uncontrolled(cohort) display_percentage(cohort_percentages(cohort)[:uncontrolled]) end def cohort_no_bp(cohort) display_percentage(cohort_percentages(cohort)[:no_bp]) end def cohort_missed_visits(cohort) display_percentage(cohort_percentages(cohort)[:missed_visits]) end def cohort_percentages(cohort) rounded_percentages({ controlled: cohort[:controlled], uncontrolled: cohort[:uncontrolled], no_bp: cohort[:no_bp], missed_visits: cohort[:missed_visits] }) end def diabetes_enabled? current_facility.diabetes_enabled? end def display_percentage(percentage) "#{percentage}%" end def last_updated_at statistics.dig(:metadata, :last_updated_at) end def statistics @statistics ||= Rails.cache.fetch(statistics_cache_key, expires_in: EXPIRE_STATISTICS_CACHE_IN, force: bust_cache?) { { cohorts: cohort_stats, metadata: { is_diabetes_enabled: diabetes_enabled?, last_updated_at: RefreshReportingViews.last_updated_at ? I18n.l(RefreshReportingViews.last_updated_at) : "", formatted_next_date: display_date(Time.current + 1.day), today_string: I18n.t(:today_str) } } } end private def cohort_stats periods = Period.quarter(Date.current).previous.downto(3) CohortService.new(region: current_facility, periods: periods).call end def statistics_cache_key "user_analytics/#{current_facility.id}/dm=#{diabetes_enabled?}/#{CACHE_VERSION}" end end
# frozen_string_literal: true require 'autosign/validator/validator_base' module Autosign module Validator # Validate certificate signing requests using a simple password list. # This is not a very secure or flexible validation scheme, but is provided # because so many existing autosign policy scripts implement it. # # @example validate CSRs when the challengePassword OID is set to any of "hunter2", "opensesame", or "CPE1704TKS" # # In /etc/autosign.conf, include the following configuration: # [password_list] # password = hunter2 # password = opensesame # password = CPE1704TKS # class Passwordlist < Autosign::Validator::ValidatorBase NAME = 'password_list' private def perform_validation(password, _certname, _raw_csr) @log.debug 'validating against simple password list' @log.debug 'passwords: ' + settings.to_s result = validate_password(password.to_s) @log.debug 'validation result: ' + result.to_s result end def validate_password(password) @log.debug 'Checking if password list includes password' password_list.include?(password.to_s) end def password_list Array(settings['password']) end def validate_settings(settings) @log.debug 'validating settings: ' + settings.to_s true end end end end
Gem::Specification.new do |s| s.name = 'argshelper' s.version = '0.1.11' s.date = Time.now.strftime('%Y-%m-%d') s.summary = 'Command line arg aid' s.description = 'A simple command line argument helper' s.authors = [ "sleepless-p03t" ] s.email = 'sleepless.genesis6@gmail.com' s.files = [ "lib/argshelper.rb" ] s.homepage = 'https://rubygems.org/gems/argshelper' s.license = 'MIT' s.add_runtime_dependency('yard', '~> 0.9', '>= 0.9.20') s.metadata["yard.run"] = "yri" end
class Url include Enumerable attr_accessor :urls def initialize(key) @urls = Utils::get_webhook_urls(key).uniq return @urls end def new(key) end def each(&block) @urls.each(&block) end def <<(url) @urls << url end def delete(url) @urls.delete(url) end def uniq @urls.uniq end =begin validates_presence_of :trig_type validates_presence_of :address validates_uniqueness_of :address, scope: :trig_type validate :trig_type_is_valid def trig_type_is_valid "change" == :trig_type || "shelve" == :trig_type || "form" == :trig_type end =end end
# frozen_string_literal: true class CreateProducts < ActiveRecord::Migration[5.2] def change create_table :products do |table| table.belongs_to :category, index: true table.string :name, null: false table.string :description, null: false table.integer :price, null: false table.float :rating, null: false, default: 1.0 table.boolean :is_active, null: false, default: false table.timestamps end end end
require 'rails_helper' feature 'Vendor manages invoices' do let :vendor { FactoryGirl.create(:vendor_with_stripe_acct) } before do login_as(vendor, scope: :vendor) end scenario 'by creating new invoice' do visit new_invoice_path expect(page).to have_content 'New Invoice' fill_in 'invoice[name]', with: 'Awesome invoice' fill_in 'invoice[description]', with: Faker::Lorem.paragraph fill_in 'invoice[amount]', with: '1000' click_button 'CREATE INVOICE' expect(Invoice.count).to eq 1 expect(page).to have_content 'Invoice successfully created!' expect(page).to have_content 'INVOICES' invoice = Invoice.last expect(invoice.id_for_plan).to eq invoice.name + invoice.id.to_s plan = Stripe::Plan.retrieve(invoice.id_for_plan, stripe_account: vendor.stripe_uid) plan.delete end end
class Knight < Piece include Steppable # sorted clockwise using row, column coordinates KNIGHT = [ [-2,1], [-1,2], [1,2], [2,1], [2,-1], [1,-2], [-1,-2], [-2,-1], ] def try_moves KNIGHT end def to_s self.color == :white ? "♞ ".white : "♞ ".blue end end
puts "Hi, there!" while true answer = gets.chomp if answer == "I'm a dummy" puts "I'm not stupid" break end puts answer end
class ScreenshotWorker include Sidekiq::Worker def perform(url, slug) image_path = "/Users/fscott/Personal/projects/webnark/webnark-rails/public/screenshots" image = `/Users/fscott/Personal/projects/webnark/screenshot/make_screenshot.sh '#{url}'` if not image or image.empty? FileUtils.cp("#{image_path}/_na.png","#{image_path}/#{slug}.png") else f = File.new("#{image_path}/#{slug}.png", "wb") f.write(image) f.close end end end
shared_examples_for 'a RESTful controller with an index action' do before :each do path_name_setup end describe "handling GET /plural (index)" do before(:each) do @object = stub(@model_name) @objects = [@object] @model_class.stubs(:find).returns(@objects) do_login if needs_login? find_target_setup :plural end def do_get get :index, {}.merge(nesting_params) end it "should be successful" do do_get response.should be_success end it "should render index template" do do_get response.should render_template('index') end if has_parent? it 'should find the parent object' do @parent_class.expects(:find).with(parent_id).returns(@parent) do_get end end it "should find the objects" do @find_target.expects(:find).returns(@objects) do_get end it "should make the found objects available to the view" do do_get assigns[@model_plural.to_sym].should == @objects end if has_parent? it 'should make the parent object available to the view' do do_get assigns[@parent_name.to_sym].should == @parent end end end end shared_examples_for 'a RESTful controller with a show action' do before :each do path_name_setup end describe "handling GET /plural/1 (show)" do before(:each) do @obj_id = '1' @obj = stub(@model_name) @model_class.stubs(:find).returns(@obj) do_login if needs_login? find_target_setup end def do_get get :show, { :id => @obj_id }.merge(nesting_params) end it "should be successful" do do_get response.should be_success end it "should render the show template" do do_get response.should render_template('show') end if has_parent? it 'should find the parent object' do @parent_class.expects(:find).with(parent_id).returns(@parent) do_get end end it "should find the object requested" do @find_target.expects(:find).with(@obj_id, anything).returns(@obj) do_get end it "should make the found object available to the view" do do_get assigns[@model_singular.to_sym].should equal(@obj) end if has_parent? it 'should make the parent object available to the view' do do_get assigns[@parent_name.to_sym].should == @parent end end end end shared_examples_for 'a RESTful controller with a new action' do before :each do path_name_setup end describe "handling GET /plural/new" do before(:each) do @obj = stub(@model_name) @model_class.stubs(:find).returns(@obj) @model_class.stubs(:new).returns(@obj) do_login if needs_login? end def do_get get :new, {}.merge(nesting_params) end it "should be successful" do do_get response.should be_success end it "should render the new template" do do_get response.should render_template('new') end it "should create a new object" do @model_class.expects(:new).returns(@obj) do_get end it "should not save the new object" do @obj.expects(:save).never do_get end it "should make the new object available to the view" do do_get assigns[@model_singular.to_sym].should equal(@obj) end end end shared_examples_for 'a RESTful controller with a create action' do before :each do path_name_setup end describe "handling POST /plural (create)" do before(:each) do @obj = @model_class.new @obj_id = 1 @obj.stubs(:id).returns(@obj_id) @model_class.stubs(:new).returns(@obj) do_login if needs_login? object_path_setup end def post_with_successful_save @obj.expects(:save).returns(true) post :create, { @model_singular.to_sym => {} }.merge(nesting_params) end def post_with_failed_save @obj.expects(:save).returns(false) post :create, { @model_singular.to_sym => {} }.merge(nesting_params) end it "should create a new object" do @model_class.expects(:new).with({}).returns(@obj) post_with_successful_save end it "should redirect to the new object on a successful save" do post_with_successful_save response.should redirect_to(self.send("#{@object_path_method}_url".to_sym, *@url_args)) end it "should re-render 'new' on a failed save" do post_with_failed_save response.should render_template('new') end end end shared_examples_for 'a RESTful controller with an edit action' do before :each do path_name_setup end describe "handling GET /plural/1/edit (edit)" do before(:each) do @obj = stub(@model_name) @model_class.stubs(:find).returns(@obj) do_login if needs_login? end def do_get get :edit, { :id => "1" }.merge(nesting_params) end it "should be successful" do do_get response.should be_success end it "should render the edit template" do do_get response.should render_template('edit') end it "should find the object requested" do @model_class.expects(:find).returns(@obj) do_get end it "should make the found object available to the view" do do_get assigns[@model_singular.to_sym].should equal(@obj) end end end shared_examples_for 'a RESTful controller with an update action' do before :each do path_name_setup end describe "handling PUT /plural/1 (update)" do before(:each) do @obj_id = '1' @obj = stub(@model_name, :to_s => @obj_id) @model_class.stubs(:find).returns(@obj) do_login if needs_login? object_path_setup find_target_setup end def put_with_successful_update @obj.expects(:update_attributes).returns(true) put :update, { :id => @obj_id }.merge(nesting_params) end def put_with_failed_update @obj.expects(:update_attributes).returns(false) put :update, { :id => @obj_id }.merge(nesting_params) end if has_parent? it 'should find the parent object' do @parent_class.expects(:find).with(parent_id).returns(@parent) do_get end end it "should find the object requested" do @find_target.expects(:find).with(@obj_id).returns(@obj) put_with_successful_update end it "should update the found object" do put_with_successful_update assigns(@model_singular.to_sym).should equal(@obj) end it "should make the found object available to the view" do put_with_successful_update assigns(@model_singular.to_sym).should equal(@obj) end if has_parent? it 'should make the parent object available to the view' do do_get assigns[@parent_name.to_sym].should == @parent end end it "should redirect to the object on a successful update" do put_with_successful_update response.should redirect_to(self.send("#{@object_path_method}_url".to_sym, *@url_args)) end it "should re-render 'edit' on a failed update" do put_with_failed_update response.should render_template('edit') end end end shared_examples_for 'a RESTful controller with a destroy action' do before :each do path_name_setup end describe "handling DELETE /plural/1 (destroy)" do before(:each) do @obj_id = '1' @obj = stub(@model_name, :destroy => true) @model_class.stubs(:find).returns(@obj) do_login if needs_login? object_path_setup :plural find_target_setup end def do_delete delete :destroy, { :id => @obj_id }.merge(nesting_params) end if has_parent? it 'should find the parent object' do @parent_class.expects(:find).with(parent_id).returns(@parent) do_get end end it "should find the object requested" do @find_target.expects(:find).with(@obj_id).returns(@obj) do_delete end it "should call destroy on the found object" do @obj.expects(:destroy).returns(true) do_delete end it "should redirect to the object list" do do_delete response.should redirect_to(self.send("#{@object_path_method}_url".to_sym, *@url_args)) end end end shared_examples_for 'a RESTful controller' do it_should_behave_like 'a RESTful controller with an index action' it_should_behave_like 'a RESTful controller with a show action' it_should_behave_like 'a RESTful controller with a new action' it_should_behave_like 'a RESTful controller with a create action' it_should_behave_like 'a RESTful controller with an edit action' it_should_behave_like 'a RESTful controller with an update action' it_should_behave_like 'a RESTful controller with a destroy action' end shared_examples_for 'a controller with login restrictions' do describe "when user is not logged in" do before :each do controller.stubs(:authorized?).returns(false) end it 'GET /plural (index) should not be accessible' do get :index response.should redirect_to(new_wants_you_to_url) end it 'GET /plural/1 (show) should not be accessible' do get :show, :id => "1" response.should redirect_to(new_wants_you_to_url) end it 'GET /plural/new should not be accessible' do get :new response.should redirect_to(new_wants_you_to_url) end it 'GET /plural/1/edit (edit) should not be accessible' do get :edit, :id => 1 response.should redirect_to(new_wants_you_to_url) end it 'POST /plural (create) should not be accessible' do post :create, {} response.should redirect_to(new_wants_you_to_url) end it 'PUT /plural/1 (update) should not be accessible' do put :update, :id => '1' response.should redirect_to(new_wants_you_to_url) end it 'DELETE /plural/1 (destroy) should not be accessible' do delete :destroy, :id => '1' response.should redirect_to(new_wants_you_to_url) end describe "request saving" do before :each do request.stubs(:request_uri).returns('fake_address') end it 'GET /plural (index) should save the requested URL' do get :index session[:return_to].should == 'fake_address' end it 'GET /plural/1 (show) should save the requested URL' do get :show, :id => "1" session[:return_to].should == 'fake_address' end it 'GET /plural/new should save the requested URL' do get :new session[:return_to].should == 'fake_address' end it 'GET /plural/1/edit (edit) should save the requested URL' do get :edit, :id => 1 session[:return_to].should == 'fake_address' end it 'POST /plural (create) should save the requested URL' do post :create, {} session[:return_to].should == 'fake_address' end it 'PUT /plural/1 (update) should save the requested URL' do put :update, :id => '1' session[:return_to].should == 'fake_address' end it 'DELETE /plural/1 (destroy) should save the requested URL' do delete :destroy, :id => '1' session[:return_to].should == 'fake_address' end end end end shared_examples_for 'a RESTful controller requiring login' do def do_login login_as Login.find(:first) end def needs_login? true end it_should_behave_like 'a RESTful controller' it_should_behave_like 'a controller with login restrictions' end #### helper methods for various setup or behavior needs # declare a default predicate for whether we need to bother with login overhead for these examples def needs_login?() false end unless defined? nesting_params def nesting_params {} end end def has_parent? parent_key end def parent_key nesting_params.keys.detect { |k| k.to_s.ends_with?('_id') } end def parent_id nesting_params[parent_key] end def parent_type parent_key.to_s.sub(/_id$/, '') end def path_name_setup @name ||= controller.class.name # => 'FoosController' @plural_path ||= @name.sub('Controller', '').tableize # => 'foos' @singular_path ||= @plural_path.singularize # => 'foo' @model_name ||= @name.to_s.sub('Controller', '').singularize # => 'Foo' @model_plural ||= @plural_path # => 'foos' @model_singular ||= @singular_path # => 'foo' @model_class ||= @model_name.constantize # => Foo if has_parent? @parent_name = parent_type.camelize @parent_class = @parent_name.constantize end end def find_target_setup(arity = :singular) find_return = case arity when :plural @objects when :singular @obj else raise "Don't know what to make parent association return" end @find_target = @model_class if has_parent? @parent_association = stub("#{@parent_name} #{@model_plural}", :find => find_return) @parent = stub(@parent_name, @model_plural.to_sym => @parent_association, :to_param => parent_id) @parent_class.stubs(:find).returns(@parent) @find_target = @parent_association end end def object_path_setup(arity = :singular) @url_args = [] @url_args.push(@obj_id) unless arity == :plural @url_args.compact! @object_path_method = instance_variable_get("@#{arity}_path") if has_parent? @object_path_method = "#{parent_type}_#{@object_path_method}" @url_args.unshift(parent_id) end end #### end of helper methods __END__ # we're not yet using this, and it's, therefore, not been exercised properly, so disabling this for now shared_examples_for 'a RESTful controller with XML support' do before :each do # @controller_name ||= controller_name # => 'FoosController' @plural_path ||= @controller_name.sub('Controller', '').tableize # => 'foos' @singular_path ||= @plural_path.singularize # => 'foo' @model_name ||= @controller_name.to_s.sub('Controller', '').singularize # => 'Foo' @model_plural ||= @plural_path # => 'foos' @model_singular ||= @singular_path # => 'foo' @model_class ||= @model_name.constantize # => Foo end describe "handling GET /plural.xml (index)" do before(:each) do @obj = stub(@model_name, :to_xml => "XML") @model_class.stubs(:find).returns(@obj) do_login if needs_login? end def do_get @request.env["HTTP_ACCEPT"] = "application/xml" get :index end it "should be successful" do do_get response.should be_success end it "should find all the objects" do @model_class.expects(:find).with(:all).returns(@obj) do_get end it "should render the found objects as xml" do @obj.expects(:to_xml).returns("XML") do_get response.body.should == "XML" end end describe "handling GET /plural/1.xml (show)" do before(:each) do @obj = stub(@model_name, :to_xml => "XML") @model_class.stubs(:find).returns(@obj) do_login if needs_login? end def do_get @request.env["HTTP_ACCEPT"] = "application/xml" get :show, :id => "1" end it "should be successful" do do_get response.should be_success end it "should find the object requested" do @model_class.expects(:find).with("1").returns(@obj) do_get end it "should render the found object as xml" do @obj.expects(:to_xml).returns("XML") do_get response.body.should == "XML" end end end shared_examples_for 'a RESTful controller with XML support requiring login' do def do_login login_as Login.find(:first) end def needs_login? true end it_should_behave_like 'a RESTful controller with XML support' end
class ApplicationController < ActionController::Base attr_accessor :current_user helper_method :current_user, :logged_in? def log_in_user!(user) session[:session_token] = user.reset_session_token! @current_user = user flash[:success] = "Successfully logged in." redirect_to user_url(user.id) end def current_user @current_user ||= User.find_by(session_token: session[:session_token]) end def logged_in? !!current_user end def require_user redirect_to new_user_url unless logged_in? end end
require 'test_helper' class TeamcommitmentsControllerTest < ActionController::TestCase def test_should_get_index get :index, {}, { :user_id => users(:fred).id } assert_response :success assert_not_nil assigns(:teamcommitments) end def test_should_get_new get :new, {}, { :user_id => users(:fred).id } assert_response :success end def test_should_create_teamcommitment assert_difference('Teamcommitment.count') do post :create, { :teamcommitment => { :id => 1234, :team_id => teams(:two).id, :project_id => projects(:one).id, :yearmonth => '2008-08-01', :days => 10, :status => 0 } }, { :user_id => users(:fred).id, :original_uri => teamcommitments_path } end assert_not_nil assigns(:teamcommitment) assert_redirected_to teamcommitments_path end def test_should_show_teamcommitment get :show, {:id => teamcommitments(:one).id}, { :user_id => users(:fred).id } assert_response :success end def test_should_get_edit get :edit, {:id => teamcommitments(:one).id}, { :user_id => users(:fred).id } assert_response :success end def test_should_update_teamcommitment assert_difference('Teamcommitment.count', 0) do put :update, {:id => teamcommitments(:unique).id, :teamcommitment => { }}, { :user_id => users(:fred).id, :original_uri => teamcommitments_path } end assert_not_nil assigns(:teamcommitment) assert_redirected_to teamcommitments_path end def test_should_destroy_teamcommitment assert_difference('Teamcommitment.count', -1) do delete :destroy, {:id => teamcommitments(:one).id}, { :user_id => users(:fred).id } end assert_redirected_to teamcommitments_path end end
require 'optics-agent/rack-middleware' require 'optics-agent/instrumenters/field' require 'optics-agent/reporting/report_job' require 'optics-agent/reporting/schema_job' require 'optics-agent/reporting/query-trace' require 'optics-agent/reporting/detect_server_side_error' require 'net/http' require 'faraday' require 'logger' require 'time' module OpticsAgent class Agent include OpticsAgent::Reporting class << self attr_accessor :logger end self.logger = Logger.new(STDOUT) attr_reader :schema, :report_traces def initialize @stats_reporting_thread = nil @query_queue = [] @semaphone = Mutex.new # set defaults @configuration = Configuration.new end def configure(&block) @configuration.instance_eval(&block) if @configuration.schema && @schema != @configuration.schema instrument_schema(@configuration.schema) end end def disabled? @configuration.disable_reporting || !@configuration.api_key || !@schema end def report_traces? @configuration.report_traces end def instrument_schema(schema) unless @configuration.api_key warn """No api_key set. Either configure it or use the OPTICS_API_KEY environment variable. """ return end if @schema warn """Agent has already instrumented a schema. Perhaps you are calling both `agent.configure { schema YourSchema }` and `agent.instrument_schema YourSchema`? """ return end @schema = schema @schema._attach_optics_agent(self) unless disabled? debug "spawning schema thread" Thread.new do debug "schema thread spawned" sleep @configuration.schema_report_delay_ms / 1000.0 debug "running schema job" SchemaJob.new.perform(self) end end end # We call this method on every request to ensure that the reporting thread # is active in the correct process for pre-forking webservers like unicorn def ensure_reporting_stats! unless @schema warn """No schema instrumented. Use the `schema` configuration setting, or call `agent.instrument_schema` """ return end unless reporting_stats? || disabled? schedule_report end end # @deprecated Use ensure_reporting_stats! instead def ensure_reporting! ensure_reporting_stats! end def reporting_connection @reporting_connection ||= Faraday.new(:url => @configuration.endpoint_url) do |conn| conn.request :retry, :max => 5, :interval => 0.1, :max_interval => 10, :backoff_factor => 2, :exceptions => [Exception], :retry_if => ->(env, exc) { true } conn.use OpticsAgent::Reporting::DetectServerSideError # XXX: allow setting adaptor in config conn.adapter :net_http_persistent end end def reporting_stats? @stats_reporting_thread != nil && !!@stats_reporting_thread.status end def schedule_report @semaphone.synchronize do return if reporting_stats? debug "spawning reporting thread" thread = Thread.new do begin debug "reporting thread spawned" report_interval = @configuration.report_interval_ms / 1000.0 last_started = Time.now while true next_send = last_started + report_interval sleep_time = next_send - Time.now if sleep_time < 0 warn 'Report took more than one interval! Some requests might appear at the wrong time.' else sleep sleep_time end debug "running reporting job" last_started = Time.now ReportJob.new.perform(self) debug "finished running reporting job" end rescue Exception => e warn "Stats report thread dying: #{e}" end end at_exit do if thread.status debug 'sending last stats report before exiting' thread.exit ReportJob.new.perform(self) debug 'last stats report sent' end end @stats_reporting_thread = thread end end def add_query(*args) @semaphone.synchronize { debug { "adding query to queue, queue length was #{@query_queue.length}" } @query_queue << args } end def clear_query_queue @semaphone.synchronize { debug { "clearing query queue, queue length was #{@query_queue.length}" } queue = @query_queue @query_queue = [] queue } end def rack_middleware # We need to pass ourselves to the class we return here because # rack will instanciate it. (See comment at the top of RackMiddleware) OpticsAgent::RackMiddleware.agent = self OpticsAgent::RackMiddleware end def graphql_middleware warn "You no longer need to pass the optics agent middleware, it now attaches itself" end def send_message(path, message) response = reporting_connection.post do |request| request.url path request.headers['x-api-key'] = @configuration.api_key request.headers['user-agent'] = "optics-agent-rb" request.body = message.class.encode(message) if @configuration.debug || @configuration.print_reports log "sending message: #{message.class.encode_json(message)}" end end if @configuration.debug || @configuration.print_reports log "got response body: #{response.body}" end end def log(message = nil) message = yield unless message self.class.logger.info "optics-agent: #{message}" end def warn(message = nil) self.class.logger.warn "optics-agent: WARNING: #{message}" end # Should we be using built in debug levels rather than our own "debug" flag? def debug(message = nil) if @configuration.debug message = yield unless message self.class.logger.info "optics-agent: DEBUG: #{message} <#{Process.pid} | #{Thread.current.object_id}>" end end end class Configuration def self.defaults { schema: nil, debug: false, disable_reporting: false, print_reports: false, report_traces: true, schema_report_delay_ms: 10 * 1000, report_interval_ms: 60 * 1000, api_key: ENV['OPTICS_API_KEY'], endpoint_url: ENV['OPTICS_ENDPOINT_URL'] || 'https://optics-report.apollodata.com' } end # Allow e.g. `debug false` == `debug = false` in configuration blocks defaults.each_key do |key| define_method key, ->(*maybe_value) do if (maybe_value.length === 1) self.instance_variable_set("@#{key}", maybe_value[0]) elsif (maybe_value.length === 0) self.instance_variable_get("@#{key}") else throw new ArgumentError("0 or 1 argument expected") end end end def initialize self.class.defaults.each { |key, value| self.send(key, value) } end end end
class MoviesController < ApplicationController def index end def show @movie = Movie.find(params[:id]) end def list @movies = Movie.all end def new @movie = Movie.new end def create @movie = Movie.new(movie_params) if @movie.save redirect_to "/movies/#{@movie.id}" else render :new end end def edit @movie = Movie.find(params[:id]) end def update @movie = Movie.find(params[:id]) if @movie.update(movie_params) redirect_to "/movies/#{@movie.id}" else render :edit end end private def movie_params params.require(:movie).permit(:title, :year_released, :description) end end
class TaskRepository def find_by_id(id) Task.find(id) end def find_by_user_and_task_id(user, task_id) user.tasks.find_by_id(task_id) end def update_from_user_and_attributes(user, attributes) task = user.tasks.find_by_id(attributes[:id]) return nil unless task attrs = validate_attrs(attributes) task.update_attributes(attrs) task end def remove_from_user_and_task_id(user, task_id) task = find_by_user_and_task_id(user, task_id) task.destroy if task task end private def validate_attrs(attributes) attrs = {} if attributes[:name].present? attrs[:name] = attributes[:name] end if attributes[:status].present? attrs[:status] = attributes[:status] end if attributes[:description].present? attrs[:description] = attributes[:description] end attrs end end
class CreateDiverseExpensesOfManagements < ActiveRecord::Migration def change create_table :diverse_expenses_of_managements do |t| t.string :name t.string :amount t.string :expenses t.string :total_delivered t.integer :cost_center_id t.float :percentage t.timestamps end end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. # protect_from_forgery with: :exceptionz include Pundit rescue_from Pundit::NotAuthorizedError, with: :permission_denied layout :page_layout # Filtering privilages. def permission_denied location = (request.referrer || after_sign_in_path_for(current_user)) redirect_to location, alert: "You are not authorized to perform this action." end private # Overwriting the sign_in redirect path method def after_sign_in_path_for(resource) if resource.has_role? :admin admins_path else if current_user.updated? home_path else edit_user_path(current_user) end end end # Overwriting the sign_out redirect path method def after_sign_out_path_for(resource_or_scope) root_path end def page_layout if current_user.nil? "landing_layout" end end end
class AddAttachmentDocument3ToProgramas < ActiveRecord::Migration[5.1] def self.up change_table :programas do |t| t.attachment :document3 end end def self.down remove_attachment :programas, :document3 end end
# frozen_string_literal: true ActiveAdmin.register Tag do permit_params :name, :color, :description index do id_column column :name do |t| status_tag(t.name, style: "background-color: #{t.color}") end column :description actions end filter :name end
# -*- coding: utf-8 -*- class Tile FREQ = { brick: 3, wood: 4, desert: 1, sheep: 4, ore: 3, wheat: 4 } SYMBOLS = { 2 => "②", 3 => "③", 4 => "④", 5 => "⑤", 6 => "⑥", 7 => "⑦", 8 => "⑧", 9 => "⑨", 10 => "⑩", 11 => "⑪", 12 => "⑫" } attr_accessor :resource, :number, :robber def initialize(resource, number, robber = false) @resource, @number = resource, number @robber = robber end def self.freqs FREQ end def short case resource when :brick then "BK" when :wood then "LG" when :desert then "DT" when :sheep then "SH" when :ore then "OR" when :wheat then "WH" else "?" end end def to_s return "⛄" if robber SYMBOLS[number] || " " end end
class TypeOfReceivedLetter < ActiveRecord::Base has_many :received_letters end
class VotesController < ApplicationController def create if params[:video_id] @element = Video.find(params[:video_id]) @voter = Tempuser.where("pku_id = ?",vote_params[:pku_id]).last if @voter @voter.like(@element) @vote = @element.votes.create(vote_params) respond_to do |f| f.js end else redirect_to timeline_path , notice: '投票失败,错误未知!' end end end def destroy if params[:video_id] @element = Video.find(params[:video_id]) @vote = @element.votes.find(params[:id]) @voter = Tempuser.where("pku_id = ?",@vote.pku_id).last if @voter @voter.unlike(@element) @vote.destroy @element.save redirect_to timeline_path , notice: '投票已取消!' else redirect_to timeline_path , notice: '取消失败,错误未知!' end end end private def vote_params params.require(:vote).permit(:video_id,:pku_id) end end
class User < ActiveRecord::Base authenticates_with_sorcery! do |config| config.authentications_class = Authentication end has_many :authentications, dependent: :destroy accepts_nested_attributes_for :authentications has_many :packs belongs_to :current_pack, class_name: 'Pack', foreign_key: 'current_pack_id' validates :password, length: { minimum: 5 }, presence: true, if: -> { new_record? || changes[:crypted_password] } validates :password, confirmation: true, if: -> { new_record? || changes[:crypted_password] } validates :password_confirmation, presence: true, if: -> { new_record? || changes[:crypted_password] } validates :email, uniqueness: true, presence: true, format: /\w+@\w+\.{1}[a-zA-Z]{2,}/ validates :name, presence: true, length: { minimum: 2 }, format: { with: /\A[a-zA-Z0-9]+\Z/ } validate :clear_words, if: proc { |a| a.name? && a.email? } scope :with_unreviewed_cards, lambda { joins(packs: :cards) .where('packs.id = users.current_pack_id AND cards.review_date <= ?', Time.zone.now).distinct } private def clear_words self.name = name.mb_chars.downcase.strip self.email = email.downcase.strip end end
class Comment < ApplicationRecord # Associations # belongs_to :parent, class_name: 'Comment', foreign_key: 'parent_id', :optional => true # has_many :children, class_name: 'Comment', foreign_key: 'parent_id', dependent: :destroy belongs_to :post belongs_to :user has_ancestry end
class Menu < ApplicationRecord has_many:orders validates :name, presence: { message: "Nama menu harus diisi" }, length: { in:3..25 } validates :price, presence: { message: "price harus diisi" }, numericality: true end
class Duck def initialize(name) @name = name end def eat puts("Duck #{@name} is eating.") end def speak puts("Duck #{@name} says Quack!") end def sleep puts("Duck #{@name} sleeps quietly.") end end class Frog def initialize(name) @name = name end def eat puts("Frog #{@name} is eating.") end def speak puts("Frog #{@name} says Crooooaaaak!") end def sleep puts("Frog #{@name} doesn't sleep; he croaks all night!") end end class Algae def initialize(name) @name = name end def grow puts("The Algae #{@name} soaks up the sun and grows") end end class WaterLily def initialize(name) @name = name end def grow puts("The water lily #{@name} floats, soaks up the sun, and grows") end end class Pond def initialize(number_animals, animal_class, number_plants, plant_class) @animal_class = animal_class @plant_class = plant_class @animals = [] number_animals.times do |i| animal = new_organism(:animal, "Animal#{i}") @animals << animal end @plants = [] number_plants.times do |i| plant = new_organism(:plant, "Plant#{i}") @plants << plant end end def simulate_one_day @plants.each {|plant| plant.grow} @animals.each {|animal| animal.speak} @animals.each {|animal| animal.eat} @animals.each {|animal| animal.sleep} end def new_organism(type, name) if type == :animal @animal_class.new(name) elsif type == :plant @plant_class.new(name) else raise "Unknown organism type: #{type}" end end end pond = Pond.new(3, Duck, 2, WaterLily) pond.simulate_one_day
# frozen_string_literal: true RSpec.describe SC::Billing::Stripe::PaymentSources::CreateOperation, :stripe do subject(:call) do described_class.new.call(user, token) end let(:stripe_customer) { Stripe::Customer.create } let(:user) { create(:user, stripe_customer_id: stripe_customer.id) } let(:token) { stripe_helper.generate_card_token } it 'creates payment source', :aggregate_failures do expect { call }.to change(::SC::Billing::Stripe::PaymentSource, :count).by(1) expect(call).to be_success end context 'when stripe raise error' do before do error = Stripe::InvalidRequestError.new('No such token', nil) StripeMock.prepare_error(error, :create_source) end it 'returns failure' do expect(call).to be_failure end end end
require 'todobot/services/base_service' module TodoBot module Lists class CreateListService < BaseService def execute if name.present? create_list else set_status end end private attr_reader :name def post_initialize(args) @name = args[:name] end def create_list new_list = user.created_lists.new(chat: chat, name: name) if new_list.save chat.update_attribute(:list_id, new_list.id) I18n.t('list.created', list: name) else new_list.errors.values.join(',') end end def set_status chat.create_list! I18n.t('list.create') end end end end
class PlayerTournamentsController < ApplicationController before_action :set_player_tournament, only: [:show, :update, :destroy] # GET /player_tournaments def index @player_tournaments = PlayerTournament.all render json: @player_tournaments end # GET /player_tournaments/1 def show render json: @player_tournament end # POST /player_tournaments def create @player_tournament = PlayerTournament.new(player_tournament_params) if @player_tournament.save render json: @player_tournament, status: :created, location: @player_tournament else render json: @player_tournament.errors, status: :unprocessable_entity end end # PATCH/PUT /player_tournaments/1 def update if @player_tournament.update(player_tournament_params) render json: @player_tournament else render json: @player_tournament.errors, status: :unprocessable_entity end end # DELETE /player_tournaments/1 def destroy @player_tournament.destroy end private # Use callbacks to share common setup or constraints between actions. def set_player_tournament @player_tournament = PlayerTournament.find(params[:id]) end # Only allow a trusted parameter "white list" through. def player_tournament_params params.require(:player_tournament).permit(:player_id, :tournament_id) end end
class User < ActiveRecord::Base has_many :performer_tasks, :class_name => "Task", :foreign_key => "performer_user_id" has_many :requester_tasks, :class_name => "Task", :foreign_key => "requester_user_id" has_many :creator_decisions, :class_name => "Decision", :foreign_key => "creator_user_id" has_many :task_shares has_many :votes has_many :shareholders has_and_belongs_to_many :user_collections validates_presence_of :username validates_length_of :username, :within => 1..50 validates_uniqueness_of :username # we intentionally allow multiple usernames with the same email # so that people can be associated with multiple projects using # different usernames if they'd like validates_presence_of :email validates_length_of :email, :within => 1..50 validates_presence_of :first_name validates_length_of :first_name, :within => 1..50 validates_presence_of :last_name validates_length_of :last_name, :within => 1..50 #validates_presence_of :password end
class MovementsController < ApplicationController helper_method :sort_column, :sort_direction, :sort_apartment_column before_action :logged_in_user before_action :movement_getter, except: [:index, :new, :create] before_action :permissions, except: [:index, :show, :children, :create] before_action :check_amount, only: [:associate_apartment] def index @movements = Movement.where("amount > ?", 0).order(sort_column + " " + sort_direction).paginate(per_page: 8, page: params[:page]) end def new @movement = Movement.new end def create flash[:danger] = 'Esta operación no está permitida' redirect_to root_path end def show end def edit end def update if @movement.update_attributes(movement_params) flash[:info] = 'Movimiento actualizado' redirect_to @movement else render 'edit' end end def destroy if @movement.parent.nil? destroy_movement else @parent = Movement.find(@movement.parent.parent_id) @parent.children.each do |child| Movement.find(child.child_id).destroy end flash[:info] = 'Se han eliminado todas los movimientos del movimiento dividido' redirect_to movements_path end end def destroy_statement @statement = Statement.find(params[:id]) @movement = Movement.find(params[:movement_id]) if @movement.statements.count > 1 if StatementMovement.find_by(statement: @statement, movement: @movement).destroy flash[:info] = "Movimiento borrado del extracto #{@statement.name}" else flash[:danger] = 'Ha ocurrido un error intentando eliminar el movimiento del extracto' end redirect_to @statement else destroy_movement end end def divide end def divide_movement amount = params[:movement][:amount].to_f if @movement.amount < amount || amount <= 0 flash[:danger] = 'La cantidad que quiere dividir es mayor que la del movimiento o tiene un valor negativo. Vuelva a intentarlo.' redirect_to divide_path(@movement) return end if @movement.apartment.nil? create_movement_duplicate(@movement.amount - amount) create_movement_duplicate(amount) redirect_to movement_children_path(@movement) else flash[:danger] = 'Por favor, desasigna el movimiento de la vivienda antes de dividir el movimiento.' redirect_to movement_path(@movement) end end def apartments @apartments = Apartment.order(sort_apartment_column + " " + sort_direction).paginate(per_page: 7, page: params[:page]) end def associate_apartment @apartment = Apartment.find(params[:apartment_id]) @apartmentmovement = ApartmentMovement.find_by(movement: @movement) if @apartmentmovement.nil? @apartmentmovement = ApartmentMovement.new(apartment: @apartment, movement: @movement) if @apartmentmovement.save @apartment.update_attribute(:balance, @apartment.balance + @movement.amount) flash[:info] = "Se ha asociado el movimiento a la vivienda #{full_name_apartment(@apartment)}" else flash[:danger] = 'Ha ocurrido un error al intentar crear la asociación del movimiento' end redirect_to apartment_path(@apartment) else old_apartment = @apartmentmovement.apartment if @apartmentmovement.update_attribute(:apartment, @apartment) flash[:info] = "Se ha cambiado la asociación a la vivienda #{full_name_apartment(@apartment)}" check_paid_pending_payments(old_apartment) old_apartment.update_attribute(:balance, old_apartment.balance - @movement.amount) @apartment.update_attribute(:balance, @apartment.balance + @movement.amount) else flash[:danger] = 'Ha ocurrido un error al intentar cambiar la asociación del movimiento' end redirect_to old_apartment end end def remove_apartment @apartment = @movement.apartment @apartmentmovement = ApartmentMovement.find_by(apartment: @movement.apartment, movement: @movement) if @apartmentmovement.destroy flash[:info] = "Movimiento desasociado de la vivienda #{full_name_apartment(@apartment)}" check_paid_pending_payments(@apartment) @apartment.update_attribute(:balance, @apartment.balance - @movement.amount) else flash[:danger] = 'Ha ocurrido un error al desasociar el movimiento de la vivienda' end redirect_to movements_path end def children end private def sort_column Movement.column_names.include?(params[:sort]) ? params[:sort] : "date" end def sort_direction %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc" end def sort_apartment_column Apartment.column_names.include?(params[:sort]) ? params[:sort] : "floor" end def movement_getter @movement = Movement.find(params[:id]) end def movement_params params.require(:movement).permit(:description, :amount) end def permissions unless current_user.admin? flash[:danger] = 'Tu cuenta no tiene permisos para realizar esa acción. Por favor, contacta con el administrador para más información.' redirect_to root_path end end def check_amount unless @movement.amount >= 0 flash[:danger] = 'El movimiento seleccionado tiene un valor negativo, no se puede añadir a una vivienda.' redirect_to statement_path(@movement.statements.first) end end def destroy_movement unless @movement.apartment.nil? check_paid_pending_payments(@movement.apartment) end if @movement.destroy flash[:info] = 'Movimiento borrado' redirect_to movements_path else flash[:danger] = 'Ha ocurrido un error al intentar eliminar el movimiento' redirect_to root_url end end def create_movement_duplicate(amount) new_movement = @movement.dup new_movement.amount = amount.round(2) new_movement.concept += " | Nº #{@movement.children.count + 1}" if new_movement.save movement_child = MovementChild.new(parent: @movement, child: new_movement) if movement_child.save flash[:info] = 'Se ha creado el movimiento duplicado' else flash[:danger] = 'Error en la creación del movimiento duplicado' redirect_to statements_path end else flash[:danger] = 'Error en la creación del movimiento duplicado' redirect_to statements_path end end end
class UsersController < ApplicationController def new @user = User.new end def create @user = User.new(params[user_params]) if @user.save redirect_to @user, notice: "Thank yo for signing up for Ribbit" else render 'new' end end private # Never trust parameters from the scary internet, only allow the white list through. def user_params params.require(:user).permit(:name, :last_name, :username, :email, :password_digest) end end
class Notification < ActiveRecord::Base belongs_to :user belongs_to :group belongs_to :status validates :description, presence: true validates :recipient, presence: true class << self def unread(user) where("id > ? and #{notify_condition}", user.last_checked_notification, user.id, groups_to_notify(user), user.id) .order(created_at: :desc).limit(5) end def read(user) where("id <= ? and #{notify_condition}", user.last_checked_notification, user.id, groups_to_notify(user), user.id) .order(created_at: :desc).limit(5) end def groups_to_notify(user) groups = [] user.characters.notified.each do |cha| groups << cha.group.id end return groups end def notify_condition 'user_id != ? and group_id in (?) and (recipient = ? or recipient = 0)' end end end
# # Cookbook Name:: wercker-develop # Recipe:: wercker-sentinel # # Copyright 2013, wercker # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # ["lxc", "expect"].each do |pkg| package pkg do action :install end end gem_package "berkshelf" do gem_binary '/usr/bin/gem1.9.3' action :install end ["/home/vagrant/wercker-sentinel", "/home/vagrant/wercker-sentinel/build-optimus"].each do |dir| directory dir do user "vagrant" group "vagrant" action :create end end ["start", "init", "npm-update", "coffeelint", "test"].each do |command| template "/home/vagrant/wercker-sentinel/#{command}" do owner "vagrant" group "vagrant" mode "0755" source "wercker-sentinel-#{command}.erb" end end optimi = ["blank", "ruby", "mysql", "optimus", "nodejs", "redis", "python", "php", "go", "rabbitmq", "postgresql", "mongodb", "deploy"] optimi.each do |optimus| template "/home/vagrant/wercker-sentinel/build-optimus/#{optimus}" do owner "vagrant" group "vagrant" mode "0755" source "wercker-sentinel-build-optimus.erb" variables( :name => optimus, :optimi => [*optimus] ) end end template "/home/vagrant/wercker-sentinel/build-optimus/_wercker" do owner "vagrant" group "vagrant" mode "0755" source "wercker-sentinel-build-optimus.erb" variables( :name => "_wercker", :optimi => ["nodejs", "mongodb"] ) end template "/home/vagrant/wercker-sentinel/build-optimus/_all" do owner "vagrant" group "vagrant" mode "0755" source "wercker-sentinel-build-optimus.erb" variables( :name => "_all", :optimi => optimi ) end
module Acl9 module ModelExtensions module ForSubject def role_for(object) (role_objects.select(&role_selecting_lambda(object)).first.try(:name) || '').downcase.to_sym end private # TODO Update gem and remove if/when my pull request gets accepted (https://github.com/be9/acl9/pull/51) def role_selecting_lambda(object) case object when Class lambda { |role| role.authorizable_type == object.to_s } when nil lambda { |role| role.authorizable.nil? } else lambda do |role| role.authorizable_type == object.class.base_class.to_s && role.authorizable_id == object.id end end end end end end
module Home::Index def self.table_name_prefix 'home_index_' end end
class Airport < ApplicationRecord # Needs a migration for indexes and references(?) has_many :departing_flights, class_name: "Flight", foreign_key: "from_id" has_many :arriving_flights, class_name: "Flight", foreign_key: "to_id" end
class AddMeasurementFieldsToTopics < ActiveRecord::Migration[5.0] def change change_table :topics do |t| t.float :min_value t.float :max_value t.float :step t.string :units_of_measurement, array: true end end end
describe RecipeManager do describe "#initialize" do it "should instantiate properly" do test = RecipeManager.new expect(test).not_to be_nil end end describe "#add_category" do before :each do @test = RecipeManager.new end it "should allow a category to be added" do @test.add_category("Meat") expect(@test.categories.include?("Meat")).to be true end it "should not add a duplicate category" do @test.add_category("Dessert") @test.add_category("Dessert") found = @test.categories.select { |e| e == "Dessert" } expect(found.count).to eq(1) end end describe "#add_recipe" do before :each do @test = RecipeManager.new end it "should add a recipe to the manager" do r = Recipe.new "Creole Chicken" @test.add_recipe(r) expect(@test.recipes.count).to eq(1) expect(@test.recipes["Uncategorized"].count).to eq(1) end it "should add a recipe with a category to the manager" do @test.add_category("Dessert") r = Recipe.new "Hot Chocolate" @test.add_recipe(r, "Dessert") expect(@test.recipes["Dessert"].count).to eq(1) end it "should throw an error if a category hasn't been added yet" do r = Recipe.new "Bourbon Chicken" expect { @test.add_recipe(r, "Dinners") }.to raise_error(RuntimeError) end end describe "#get_recipe_by_category" do before :each do @test = RecipeManager.new @test.add_category("Dinners") @test.add_category("Breakfasts") @test.add_recipe(Recipe.new("Bourbon Chicken"), "Dinners") @test.add_recipe(Recipe.new("Steak Toscano"), "Dinners") @test.add_recipe(Recipe.new("Pain Perdu"), "Breakfasts") end it "should get a list of all recipes in the given category" do items = @test.get_recipe_by_category("Dinners") expect(items.count).to eq(2) item_names = items.map { |e| e.name } expect(item_names).to eq(["Bourbon Chicken", "Steak Toscano"]) end end end
#!/usr/bin/env ruby require 'date' require 'optparse' def make_calendar(year, month) caption = "#{month}月 #{year}".center(20) header = '日 月 火 水 木 金 土' first = Date.new(year, month, 1) last = Date.new(year, month, -1) spaces = Array.new(first.wday, '') days = [*first.day..last.day] weeks = (spaces + days).each_slice(7).map do |week| week.map {|day| day.to_s.rjust(2)}.join(' ') end [caption, header] + weeks end params = ARGV.getopts('y:m:') year = params['y']&.to_i || Date.today.year month = params['m']&.to_i || Date.today.month puts make_calendar(year, month) puts ''
module Enumerable def my_each if !block_given? return self else for i in self yield(i) end end end def my_each_with_index if !block_given? return self else for i in self yield(i,self.index(i)) end end end def my_select arr = [] for i in self if yield(i) arr.push(i) end end return arr end end puts [1,2,3,4,5].my_select { |num| num.even? }
# encoding: UTF-8 require "minitest_helper" require "ostruct" require "airbrussh/command_formatter" class Airbrussh::CommandFormatterTest < Minitest::Test def setup @sshkit_command = OpenStruct.new( :host => host("deployer", "12.34.56.78"), :options => { :user => "override" }, :runtime => 1.23456, :failure? => false ) @sshkit_command.define_singleton_method(:to_s) do "/usr/bin/env echo hello" end @command = Airbrussh::CommandFormatter.new(@sshkit_command, 0) end def test_format_output assert_equal("01 hello", @command.format_output("hello\n")) end def test_start_message assert_equal("01 \e[0;33;49mecho hello\e[0m", @command.start_message) end def test_exit_message_success assert_equal( "\e[0;32;49m✔ 01 deployer@12.34.56.78\e[0m 1.235s", @command.exit_message ) end def test_exit_message_failure @command.stub(:failure?, true) do assert_equal( "\e[0;31;49m✘ 01 deployer@12.34.56.78\e[0m "\ "1.235s", @command.exit_message ) end end def test_uses_ssh_options_if_host_user_is_absent @sshkit_command.host = host(nil, "12.34.56.78", :user => "sshuser") assert_equal( "\e[0;32;49m✔ 01 sshuser@12.34.56.78\e[0m 1.235s", @command.exit_message ) end def test_shows_hostname_only_if_no_user @sshkit_command.host = host(nil, "12.34.56.78") assert_equal( "\e[0;32;49m✔ 01 12.34.56.78\e[0m 1.235s", @command.exit_message ) end def test_handles_nil_position_gracefully command = Airbrussh::CommandFormatter.new(@sshkit_command, nil) assert_equal("01 hello", command.format_output("hello\n")) end private def host(user, hostname, ssh_options={}) SSHKit::Host.new( :user => user, :hostname => hostname, :ssh_options => ssh_options ) end end
class RentsController < ApplicationController before_filter :authenticate_user! before_filter :set_artwork layout 'kunst' # Get content about rent process and show it to user # def new @page = Page.find_by_title('Huren bij Xposers') end # Register new rental and emails user # def create @rent = @artwork.rents.new if @rent.confirm(current_user) Kunstmail.rent(current_user, @artwork).deliver redirect_to root_url, notice: "Check your email for further instructions" end end private def set_artwork @artwork = Kunstvoorwerp.find(params[:artwork_id]) redirect_to root_url, notice: "Artwork cant be hired" if @artwork.status > 0 end end
LightningTalker::Application.routes.draw do resources :users resources :topics do put 'claim' => 'topics#claim', on: :member put 'unclaim' => 'topics#unclaim', on: :member get 'schedule' => 'topics#schedule', on: :collection end resources :sessions, only: [:new, :create] get 'sign_up' => 'users#new', as: 'sign_up' get 'sign_in' => 'sessions#new', as: 'sign_in' get 'sign_out' => 'sessions#destroy', as: 'sign_out' root :to => 'topics#index' end
class AddConfigToCrawler < ActiveRecord::Migration def self.up add_column :crawlers, :config, :text, :null => false end def self.down remove_column :crawlers, :config end end
# Usage: $ ruby find_common_layers.rb path/to/folder [path_filter] [layer_filter] # # Reads a sample (n=500) of the grib2 inventories deeper than the given directory and outputs the common layers to STDOUT. # # Uncommon layers are output to STDERR. # # Optional `path_filter` is straight Ruby you can provide. The path is in a `path` variable--just be sure to return a boolean. require "fileutils" require "json" NAME_NORMALIZATION_SUBSTITUTIONS = JSON.parse(File.read(File.expand_path("../layer_name_normalization_substitutions.json", __FILE__))) root_path = ARGV[0] || (STDERR.puts "Usage: $ ruby find_common_layers.rb path/to/folder [path_filter] [layer_filter]"; exit 1) path_filter = ARGV[1] layer_filter = ARGV[2] sample_count = 500 FileUtils.cd root_path grib2_paths = Dir.glob("**/*").grep(/.gri?b2\z/i).select { |path| path_filter ? eval(path_filter) : true } def normalize_inventory_line(line) NAME_NORMALIZATION_SUBSTITUTIONS.each do |target, replacement| line = line.gsub(target, replacement) end line end STDERR.print "Sampling #{sample_count} files to find common layers" # c.f. Inventories.jl ENGLISH_NUMBERS = { 0 => "zero", 1 => "one", 2 => "two", 3 => "three", 4 => "four", 5 => "five", 6 => "six", 7 => "seven", 8 => "eight", 9 => "nine", 10 => "ten", 11 => "eleven", 12 => "twelve", 13 => "thirteen", 14 => "fourteen", 15 => "fifteen", 16 => "sixteen", 17 => "seventeen", 18 => "eighteen", 19 => "nineteen", 20 => "twenty", 30 => "thirty", 40 => "fourty", 50 => "fifty", 60 => "sixty", 70 => "seventy", 80 => "eighty", 90 => "ninety", } def int_to_english(n, elide_zero: false) if n < 0 "negative " + int_to_english(-n) elsif n == 0 && elide_zero "" elsif n >= 1_000_000_000_000 trillions, rest = n.divmod(1_000_000_000_000) int_to_english(trillions) + " trillion " + int_to_english(rest, elide_zero: true) elsif n >= 1_000_000_000 billions, rest = n.divmod(1_000_000_000) int_to_english(billions) + " billion " + int_to_english(rest, elide_zero: true) elsif n >= 1_000_000 millions, rest = n.divmod(1_000_000) int_to_english(millions) + " million " + int_to_english(rest, elide_zero: true) elsif n >= 1_000 thousands, rest = n.divmod(1_000) int_to_english(thousands) + " thousand " + int_to_english(rest, elide_zero: true) elsif n >= 100 hundreds, rest = n.divmod(100) int_to_english(hundreds) + " hundred " + int_to_english(rest, elide_zero: true) elsif ENGLISH_NUMBERS[n] ENGLISH_NUMBERS[n] else # 21 <= n <= 99 and n not divisible by 10 tens, rest = n.divmod(10) ENGLISH_NUMBERS[tens*10] + "-" + ENGLISH_NUMBERS[rest] end.strip end # "7 hour fcst" => "hour fcst" # "11-12 hour acc fcst" => "one hour long acc fcst" # "11-12 hour max fcst" => "one hour long max fcst" # c.f. Inventories.jl def generic_forecast_hour_str(forecast_hour_str) # "11-12" => "one hour long" forecast_hour_str.gsub(/^\d+-\d+\s+hour/) do |range_str| start, stop = range_str.split(/[\- ]/)[0..1].map(&:to_i) int_to_english(stop - start) + " hour long" end.gsub(/\s*\d+\s*/, "") # "7 hour fcst" => "hour fcst" end # "7 hour fcst" => 7 # "11-12 hour acc fcst" => 12 # "11-12 hour max fcst" => 12 # c.f. Inventories.jl def extract_forecast_hour(forecast_hour_str) Integer(forecast_hour_str[/(\d+) hour (\w+ )?fcst/, 1]) end inventories = grib2_paths. sample(sample_count). map do |grib2_path| STDERR.print "."; STDERR.flush inventory = `wgrib2 #{grib2_path} -s -n` if $?.success? inventory else STDERR.print "SKIP"; STDERR.flush nil end end. compact. flat_map do |inventory_str| # STDERR.puts inventory_str # STDERR.puts inventory_str. split("\n"). map { |line| normalize_inventory_line(line) }. select { |line| line =~ /:(\d+-)?\d+ hour (\w+ )?fcst:/ }. # Exclude "0-1 day acc fcst" # select { |line| line !~ /:APCP:/ }. # Skip APCP Total Precipitation fields; for SREF they seem to be off by an hour and mess up the group_by below map { |line| line.split(":") }. group_by { |_, _, _, _, _, x_hours_fcst_str, _, _| extract_forecast_hour(x_hours_fcst_str) }. # SREF forecasts contain multiple forecast hours in the same file: split them apart. map { |x_hours_fcst, inventory_lines| inventory_lines } end.map do |inventory_lines| inventory_lines.map { |_, _, _, abbrev, desc, x_hours_fcst_str, prob_level, _| [abbrev, desc, generic_forecast_hour_str(x_hours_fcst_str), prob_level] } end common = inventories.reduce(:&) uncommon = inventories.reduce(:|) - common if layer_filter common_filtered = common.select { |abbrev, desc, hours_fcst, prob_level| eval(layer_filter) } else common_filtered = common end rejected_by_filter = common - common_filtered STDERR.puts puts common_filtered.map { |key_parts| key_parts.join(":") }.join("\n") if uncommon.any? STDERR.puts STDERR.puts "Uncommon layers:" STDERR.puts uncommon.map { |key_parts| key_parts.join(":") }.join("\n") end if rejected_by_filter.any? STDERR.puts STDERR.puts "Rejected layers:" STDERR.puts rejected_by_filter.map { |key_parts| key_parts.join(":") }.join("\n") end
## # *this class controls the orders' actions # *created using scaffold # *the class methods are all common controller methods # [index] the index page for model is defined # [show] the page for each specific model instance eg. cart[6] is defined # [new] the page for creating new model instances is defined # [create] the stuff done after the new instance created # [edit] the edit page for model instances is defined # [update] the method called after edit # [destroy] mothod for destruction of model instances class OrdersController < ApplicationController ##--:method: before_filter------------------------------------------- # using the following before_filter users cannot directly access: # * www.site.com/orders # * www.site.com/orders/[i] before_filter :access_denied , :only => [:index ,:show] def access_denied redirect_to root_url , :notice => 'You are not authorized to see this page!' end #----------------------------------------------------------------- # GET /orders # GET /orders.json def index @orders = Order.paginate :page=>params[:page], :order=>'created_at desc', :per_page => 10 respond_to do |format| format.html # index.html.erb format.json { render json: @orders } end end # GET /orders/1 # GET /orders/1.json def show @order = Order.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @order } end end # GET /orders/new # GET /orders/new.json def new @cart = current_cart if @cart.line_items.empty? redirect_to root_url, :notice => "Your cart is empty" elsif current_user.nil? redirect_to root_url, :notice => "You must first sign in to place order" return else @order = Order.new respond_to do |format| format.html # new.html.erb format.json { render json: @order } end end end # GET /orders/1/edit def edit @order = Order.find(params[:id]) end # POST /orders # POST /orders.json def create @order = Order.new(params[:order]) @order.add_line_items_from_cart(current_cart) @my_order = @order.id respond_to do |format| if @order.save if @order.pay_type == 'Credit card' Cart.destroy(session[:cart_id]) session[:cart_id] = nil format.html { redirect_to(payment_url, :notice => 'Thank you for your order.Please confirm to connect to bank payment') } format.xml { render :xml => @order, :status => :created, :location => @order } elsif @order.pay_type== "Direct pay after delivery" Cart.destroy(session[:cart_id]) session[:cart_id] = nil format.html { redirect_to(root_url, :notice => 'Thank you for your order.' ) } format.xml { render :xml => @order, :status => :created, :location => @order } end else format.html { render action: "new" } format.json { render json: @order.errors, status: :unprocessable_entity } end end end def reset_cart Cart.destroy(session[:cart_id]) session[:cart_id] = nil end def payment @my_order ||= Order.find_by_email(current_user[:email]) if current_user[:email] @total_order_price = 0 @my_order.line_items.each do |item| @total_order_price+=item.total_price end end # PUT /orders/1 # PUT /orders/1.json def update @order = Order.find(params[:id]) respond_to do |format| if @order.update_attributes(params[:order]) format.html { redirect_to @order, notice: 'Order was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @order.errors, status: :unprocessable_entity } end end end # DELETE /orders/1 # DELETE /orders/1.json def destroy @order = Order.find(params[:id]) @order.destroy respond_to do |format| format.html { redirect_to orders_url } format.json { head :no_content } end end end
require 'spec_helper' require 'rails_helper' require Rails.root.join("spec/helpers/restaurant_helper.rb") describe RestaurantsController, "test" do context "Index action" do before :each do @admin = create(:user) @admin.update_column(:admin_role, true) @user1 = create(:user) @restaurant = create(:restaurant, {user_id: @user1.id}) end it "case 1: not login" do get "index" response.should redirect_to(new_user_session_path) end it "case 2: login, owner" do sign_in @user1 get "index" response.should redirect_to(root_path) end it "case 3: login, admin" do sign_in @admin get "index" response.should render_template('index') expect(assigns[:restaurants]).to include @restaurant end end end
# prereqs: iterators, hashes, conditional logic # Given a hash with numeric values, return the key for the smallest value def key_for_min_value(name_hash) min_k = nil min_v = nil name_hash.each do |key, value| # returns the KEY of the smallest VALUE in the hash if min_v == nil min_v = value min_k = key elsif min_v > value min_v = value min_k = key end end min_k end
class REntriesToLinksController < ApplicationController before_action :set_r_entries_to_link, only: [:show, :edit, :update, :destroy] # GET /r_entries_to_links # GET /r_entries_to_links.json def index @r_entries_to_links = REntriesToLink.all end # GET /r_entries_to_links/1 # GET /r_entries_to_links/1.json def show end # GET /r_entries_to_links/new def new @r_entries_to_link = REntriesToLink.new end # GET /r_entries_to_links/1/edit def edit end # POST /r_entries_to_links # POST /r_entries_to_links.json def create @r_entries_to_link = REntriesToLink.new(r_entries_to_link_params) respond_to do |format| if @r_entries_to_link.save format.html { redirect_to @r_entries_to_link, notice: 'R entries to link was successfully created.' } format.json { render action: 'show', status: :created, location: @r_entries_to_link } else format.html { render action: 'new' } format.json { render json: @r_entries_to_link.errors, status: :unprocessable_entity } end end end # PATCH/PUT /r_entries_to_links/1 # PATCH/PUT /r_entries_to_links/1.json def update respond_to do |format| if @r_entries_to_link.update(r_entries_to_link_params) format.html { redirect_to @r_entries_to_link, notice: 'R entries to link was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @r_entries_to_link.errors, status: :unprocessable_entity } end end end # DELETE /r_entries_to_links/1 # DELETE /r_entries_to_links/1.json def destroy @r_entries_to_link.destroy respond_to do |format| format.html { redirect_to r_entries_to_links_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_r_entries_to_link @r_entries_to_link = REntriesToLink.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def r_entries_to_link_params params.require(:r_entries_to_link).permit(:r_entry_id, :r_link_id, :properties) end end
class Fight < ActiveRecord::Base belongs_to :player belongs_to :enemy end
class Task < ApplicationRecord #validations validates :name, presence: true #associations belongs_to :project has_many :comments module Status FRESH = 'fresh'.freeze DONE = 'done'.freeze ALL = Task::Status.constants.map{ |roles| Task::Status.const_get(roles) }.flatten.uniq end module Priority HIGH = 'high'.freeze MEDIUM = 'medium'.freeze LOW = 'low'.freeze ALL = Task::Priority.constants.map{ |roles| Task::Priority.const_get(roles) }.flatten.uniq end enum status: [ :fresh, :done] enum priority: [ :high, :medium, :low] end
#!/usr/bin/env ruby require 'optparse' require 'ostruct' require 'json' require_relative '../lib/WRAzureNetworkManagement' require_relative '../lib/WRAzureWebServers' require_relative '../lib/CSRELogger' @options = OpenStruct.new @options[:location] = 'WestEurope' def parse_args(args) opt_parser = OptionParser.new do |opts| opts.banner = 'Usage: tester.rb [options]' opts.on('-c client_name', '--client_name ClientName', 'The Servie Principal name in Azure AD - Required') do |client_name| @options[:client_name] = client_name end opts.on('-e Environment', '--environment Environment', 'Environment you are testing, i.e. dev, prod etc etc') do |environment| @options[:environment] = environment end opts.on('-r ResourceGroup', '--resourcegroup Environment', 'Environment you are testing, i.e. dev, prod etc etc') do |resource_group| @options[:resource_group] = resource_group end opts.on('-v VNet', '--vnet VNet', 'VNet you are testin') do |vnet| @options[:vnet] = vnet end opts.on('-s System', '--system System', 'The system are you testing') do |system| @options[:system] = system end opts.on('-t test', '--test Test', 'The test you would like to perform') do |test| @options[:test] = test end end opt_parser.parse!(args) # if @options[:client_name].nil? || @options[:environment].nil? # puts 'you\'re missing the --client_name or --environment option. You must specify --client_name and --environment' # exit # end # raise OptionParser::MissingArgument if @options[:cname].nil? end parse_args(ARGV) client_name = @options.client_name environment = @options.environment vnet = @options.vnet resource_group = @options.resource_group log_level = 'INFO' log_level = ENV['CSRE_LOG_LEVEL'] unless ENV['CSRE_LOG_LEVEL'].nil? @csrelog = CSRELogger.new(log_level, 'STDOUT') # test network if resource_group && vnet net_tester = WRAzureNetworkManagement.new(client_name: client_name, environment: environment) subnet_status = net_tester.list_available_ips(resource_group: resource_group, vnet: vnet) puts subnet_status end case @options.system when 'web_servers' web_tester = WRAzureWebServers.new(client_name: client_name, environment: environment) case @options.test when 'get_live_cluster' @csrelog.info("The live cluster is: #{web_tester.get_live_colour()}") when 'check_wr_web_servers' @csrelog.info("The live cluster status is: #{web_tester.check_wr_web_servers()}") end end
class Recipe < ApplicationRecord paginates_per 2 has_one_attached :image # could also attached more than one image wiht has_many_attached end
# Copyright (C) 2008-2015 Kouhei Sutou <kou@clear-code.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. require 'pathname' require 'tdiary/io/default' module TDiary class GitIO < IO::Default def transaction( date, &block ) dirty = TDiaryBase::DIRTY_NONE result = super( date ) do |diaries| dirty = block.call( diaries ) diaries = diaries.reject {|_, diary| /\A\s*\Z/ =~ diary.to_src} dirty end unless (dirty & TDiaryBase::DIRTY_DIARY).zero? Dir.chdir(@data_path) do file_path = Pathname.new( @dfile ) data_dir_path = Pathname.new( @data_path ) relative_file_path = file_path.relative_path_from( data_dir_path ) run( "git", "add", relative_file_path.to_s ) run( "git", "commit", "-m", "Update #{date.strftime('%Y-%m-%d')}" ) run( "git", "push" ) end end result end private def run( *command ) command = command.collect {|arg| escape_arg( arg )}.join(' ') result = `#{command} 2>&1` unless $?.success? raise "Failed to run #{command}: #{result}" end result end def escape_arg( arg ) "'#{arg.gsub( /'/, '\\\'' )}'" end end end # Local Variables: # ruby-indent-level: 3 # tab-width: 3 # indent-tabs-mode: t # End:
module AdminLte class AuthorizedstaffsController < AdminLte::ApplicationController respond_to :json, :html before_action :set_authoriziedstaff, only: [:show, :edit, :update, :destroy] # GET /faculties # GET /faculties.json def index @authoriziedstaffs = Authorizedstaff.all end # GET /faculties/1 # GET /faculties/1.json` def show end # GET /faculties/new def new @authoriziedstaffs = Authoriziedstaff.new @url = new_admin_lte_authoriziedstaff_path end # GET /faculties/1/edit def edit @url = admin_lte_authorized_staff_path(@authoriziedstaff) end # POST /faculties # POST /faculties.json def create # binding.pry @authoriziedstaff = Authoriziedstaff.new(authoriziedstaff_params) if @authoriziedstaff.save flash[:notice] = t('admin.authoriziedstaffs.create.success') respond_with :edit, :admin_lte, @authoriziedstaff else flash[:warning] = @authoriziedstaff.errors.full_messages.uniq.join(', ') respond_with :new, :admin_lte, :authoriziedstaff end end # PATCH/PUT /faculties/1 # PATCH/PUT /faculties/1.json def update if @authoriziedstaff.update(authoriziedstaff_params) flash[:notice] = t('admin.faculties.update.success') respond_with :edit, :admin_lte, @authoriziedstaff else flash[:warning] = @authoriziedstaff.errors.full_messages.uniq.join(', ') respond_with :edit, :admin_lte, :authoriziedstaff end end # DELETE /faculties/1 # DELETE /faculties/1.json def destroy @authoriziedstaff.destroy respond_to do |format| format.html { redirect_to admin_lte_authorizedstaff_path, notice: t('admin.faculties.destroy.success') } # format.json { head :no_content } end end private def set_authoriziedstaff @authoriziedstaff = Authoriziedstaff.find(params[:id]) end def authorizedstaff_params params.require(:authorizedstaff).permit(:name, :user_id) end end end
module Flint def self.declare(*args) Sass::Script::Functions.declare(*args) end # # Use ruby functions # # @return {Bool} # def flint_use_ruby() Sass::Script::Bool.new(true) end # # Fetch value from map # # @param {Map} map - map to fetch value from # @param {ArgList} keys - list of keys to traverse # # @return {*} # def flint_ruby_map_fetch(map, *keys) assert_type map, :Map, :map result = map keys.each { |key| result.nil? ? break : result = result.to_h.fetch(key, nil) } unless result.nil? result else Sass::Script::Bool.new(false) end end declare :flint_ruby_map_fetch, :args => [:map, :keys], :var_args => true # # Joins all elements of list with passed glue # # @param {List} list # @param {String} glue # # @return {String} # def flint_ruby_list_to_str(list, glue) assert_type list, :List, :list assert_type glue, :String, :glue arr = list.to_a.flatten.map { |item| item.value } Sass::Script::String.new(arr.join(glue.value)) end declare :flint_ruby_list_to_str, :args => [:list, :glue] # # Turn string into a flat list # # @param {String} string - string to operate on # @param {String} separator - item to find which separates substrings # @param {String} ignore - removes remaining string beyond item # # @return {List} # def flint_ruby_str_to_list(string, separator, ignore) assert_type string, :String, :string assert_type separator, :String, :separator assert_type ignore, :String, :ignore # Remove everything after ignore, split with separator items = string.value[/[^#{ignore}]+/].split(separator.value) if items.count == 1 Sass::Script::String.new(items[0], :comma) else Sass::Script::List.new(items.map { |i| Sass::Script::String.new(i) }, :comma) end end declare :flint_ruby_str_to_list, :args => [:string, :separator, :ignore] # # Replace substring with string # # @param {String} string - string that contains substring # @param {String} find - substring to replace # @param {String} replace - new string to replace sub with # # @return {String} # def flint_ruby_str_replace(string, find, replace) assert_type string, :String, :string assert_type find, :String, :find assert_type replace, :String, :replace Sass::Script::String.new(string.value.gsub(find.value, replace.value)) end declare :flint_ruby_str_replace, :args => [:string, :find, :replace] end
class CreateSpeakers < ActiveRecord::Migration def self.up create_table :speakers do |t| t.string :name t.text :bio t.string :presentation t.text :description t.string :filename t.integer :size t.string :content_type t.timestamps end add_index :speakers, :name end def self.down drop_table :speakers end end
require 'fileutils' Then(/^I should receive a file '([^']*)' of type '([^']*)' matching:$/) do |file_name, mime_type, table| begin content_type = page.response_headers['Content-Type'] content_disposition = page.response_headers['Content-Disposition'] expect(content_type).to eq(mime_type) expect(content_disposition).to match(file_name) rescue Capybara::NotSupportedByDriverError puts 'Unable to test response headers with this javascript driver' end table.headers.each do |header| expect(page).to have_content(header) end end #This is intended for a javascript driver that is able to allow header inspection Then(/^I should receive a file '([^']*)' of type '([^']*)'$/) do |file_name, mime_type| expect(page.response_headers['Content-Type']).to eq(mime_type) expect(page.response_headers['Content-Disposition']).to match(file_name) end #This doesn't actually test the mime_type, which we'd want to check from the response headers # This is intended for use with a selenium that actually does a download # We can't check the Content-Type header, though we may be able to check the file in other ways # dispatching on the mime_type. Then(/^I should have downloaded a file '([^']*)' of type '([^']*)'$/) do |file_name, mime_type| expect(File.exist?(File.join(CAPYBARA_DOWNLOAD_DIR, file_name))).to be_truthy end
require "hotel_beds/parser" module HotelBeds module Parser class CancellationPolicy include HotelBeds::Parser attribute :amount, attr: "amount" attribute :from_date, attr: "dateFrom" attribute :from_time, attr: "time" attribute :add_to_cart_from_date, selector: "DateTimeFrom", attr: "date" attribute :add_to_cart_from_time, selector: "DateTimeFrom", attr: "time" attribute :add_to_cart_end_date, selector: "DateTimeTo", attr: "date" attribute :add_to_cart_amount, selector: "Amount" end end end
# -*- mode: ruby -*- # vi: set ft=ruby : # Tested with Vagrant 2.0.2 https://releases.hashicorp.com/vagrant/2.0.2/ require 'fileutils' require 'find' require 'pathname' vagrant_use_proxy = ENV.fetch('VAGRANT_USE_PROXY', nil) http_proxy = ENV.fetch('HTTP_PROXY', nil) box_name = ENV.fetch('BOX_NAME', 'trusty64') # for downloading boxes set to true export BOX_DOWNLOAD=true;vagrant up box_download = ENV.fetch('BOX_DOWNLOAD', false) box_download = (box_download =~ (/^(true|t|yes|y|1)$/i)) # e.g. for Windows test, export BOX_NAME='windows7' for ubuntu test, export BOX_NAME='trusty64' @debug = ENV.fetch('DEBUG', 'false') # legacy default, left intact for the reference box_basedir = ENV.fetch('BOX_BASEDIR', nil) box_memory = ENV.fetch('BOX_MEMORY', '1024') box_cpus = ENV.fetch('BOX_CPUS', '2') box_gui = ENV.fetch('BOX_GUI', '') box_bootstrap = ENV.fetch('BOX_BOOTSTRAP', false) box_chefdk = ENV.fetch('BOX_CHEFDK', false) @debug = (@debug =~ (/^(true|t|yes|y|1)$/i)) def file_dir_or_symlink_exists?(filepath) status = false # # the 'pathname' methods seem to work a little better # $stderr.puts ('Inspecting ' + filepath ) # if File.exist?(filepath) # $stderr.puts (filepath + ' is a file') # status = true # end # if Dir.exist?(filepath) # $stderr.puts (filepath + ' is a directory') # status = true # end # if File.symlink?(filepath) # $stderr.puts (filepath + ' is a symlink') # status = true # end o = Pathname.new(filepath) if o.exist? if o.file? if @debug $stderr.puts (filepath + ' is a file') end status = true end if o.directory? if @debug $stderr.puts (filepath + ' is a directory') end status = true end if o.symlink? if @debug $stderr.puts (filepath + ' is a symlink') end status = true end end status end if box_basedir.nil? basedir = ENV.fetch('USERPROFILE', '') basedir = ENV.fetch('HOME', '') if basedir == '' basedir = basedir.gsub('\\', '/') else # e.g. export BOX_BASEDIR='/media/sergueik/Windows8_OS/Users/Serguei' # NOTE: with a filesystem freespace-constrained environment also need # symlink the '~/VirtualBox VMs' and '~/.vagrant.d/boxes/#{box_name}' to # point to matching directories under ${BOX_BASEDIR} basedir = box_basedir home = ENV.fetch('HOME') unless file_dir_or_symlink_exists? "#{home}/VirtualBox VMs" if @debug $stderr.puts 'Creating symlink ' + "#{box_basedir}/VirtualBox VMs" + ' to ' + "#{home}/VirtualBox VMs" end File.symlink "#{box_basedir}/VirtualBox VMs", "#{home}/VirtualBox VMs" end if ! box_name.nil? vagrant_box_dir = ".vagrant.d/boxes/#{box_name}" unless file_dir_or_symlink_exists? "#{home}/#{vagrant_box_dir}" if @debug $stderr.puts 'Creating symlink ' +"#{home}/#{vagrant_box_dir}" + ' to ' + "#{box_basedir}/#{vagrant_box_dir}" end File.symlink "#{box_basedir}/vagrant.d/boxes/#{box_name}", "#{home}/vagrant.d/boxes/#{box_name}" end end end if @debug puts "box_name=#{box_name}" puts "box_gui=#{box_gui}" puts "box_cpus=#{box_cpus}" puts "box_memory=#{box_memory}" end VAGRANTFILE_API_VERSION = '2' Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| # Localy cached images case box_name when /trusty32/ config_vm_box = 'ubuntu' box_filepath = "#{basedir}/Downloads/trusty-server-cloudimg-i386-vagrant-disk1.box" config_vm_box_url = "file://#{box_filepath}" box_base_url = 'https://cloud-images.ubuntu.com/vagrant/trusty/current' box_download_url = "#{box_base_url}/trusty-server-cloudimg-i386-vagrant-disk1.box" if box_download $stderr.puts "Downloading #{box_download_url} to #{box_filepath}" %x|curl -k -L #{box_download_url} -o #{box_filepath}| end when /trusty64/ config_vm_box = 'ubuntu' config_vm_default = 'linux' box_filepath = "#{basedir}/Downloads/trusty-server-cloudimg-amd64-vagrant-disk1.box" config_vm_box_url = "file://#{box_filepath}" box_base_url = 'https://cloud-images.ubuntu.com/vagrant/trusty/current' box_download_url = "#{box_base_url}/trusty-server-cloudimg-amd64-vagrant-disk1.box" if box_download $stderr.puts "Downloading #{box_download_url} to #{box_filepath}" %x|curl -k -L #{box_download_url} -o #{box_filepath}| end else # cached boxes from https://developer.microsoft.com/en-us/microsoft-edge/tools/vms/ # see also https://app.vagrantup.com/designerror/boxes/windows-7 config_vm_default = 'windows' config_vm_box_bootstrap = box_bootstrap if box_name =~ /xp/ config_vm_box = 'windows_xp' config_vm_box_url = "file://#{basedir}/Downloads/IE8.XP.For.Vagrant.box" elsif box_name =~ /2008/ config_vm_box = 'windows_2008' config_vm_box_url = "file://#{basedir}/Downloads/windows-2008R2-serverstandard-amd64_virtualbox.box" elsif box_name =~ /2012/ config_vm_box = 'windows_2012' config_vm_box_url = "file://#{basedir}/Downloads/windows_2012_r2_standard.box" else config_vm_box = 'windows7' config_vm_box_url = "file://#{basedir}/Downloads/vagrant-win7-ie11.box" end end config.vm.define config_vm_default do |config| config.vm.box = config_vm_box config.vm.box_url = config_vm_box_url puts "Configuring '#{config.vm.box}'" # Configure guest-specific port forwarding if config.vm.box !~ /windows/ config.vm.network 'forwarded_port', guest: 5901, host: 5901, id: 'vnc', auto_correct: true config.vm.host_name = 'linux.example.com' config.vm.hostname = 'linux.example.com' else # clear HTTP_PROXY to prevent # WinRM::WinRMHTTPTransportError: Bad HTTP response returned from server (503) # also often seen between windows hosts and windows guests, not solved # User: vagrant # Endpoint: http://127.0.0.1:5985/wsman # Message: WinRM::WinRMAuthorizationError # https://github.com/chef/knife-windows/issues/143 ENV.delete('HTTP_PROXY') # NOTE: WPA dialog blocks chef solo and makes Vagrant fail on modern.ie box config.vm.communicator = 'winrm' config.winrm.username = 'vagrant' config.winrm.password = 'vagrant' config.vm.guest = :windows config.windows.halt_timeout = 120 # Port forward WinRM and RDP # https://www.vagrantup.com/docs/boxes/base.html # https://codeblog.dotsandbrackets.com/vagrant-windows/ # does not seem to work from Windows host - pending validation from linux host config.vm.network :forwarded_port, guest: 3389, host: 3389, id: 'rdp', auto_correct: true config.vm.network :forwarded_port, guest: 5985, host: 5985, id: 'winrm', auto_correct:true config.vm.network :forwarded_port, guest: 5986, host: 5986, auto_correct:true config.vm.network :forwarded_port, guest: 389, host: 1389 config.vm.host_name = 'windows7' config.vm.boot_timeout = 120 # Ensure that all networks are set to 'private' config.windows.set_work_network = true # on Windows, use default data_bags share end # Configure common synced folder config.vm.synced_folder './' , '/vagrant' # Configure common port forwarding config.vm.network 'forwarded_port', guest: 4444, host: 4444, id: 'selenium', auto_correct:true config.vm.network 'forwarded_port', guest: 3000, host: 3000, id: 'reactor', auto_correct:true config.vm.provider 'virtualbox' do |vb| vb.gui = box_gui vb.customize ['modifyvm', :id, '--cpus', box_cpus ] vb.customize ['modifyvm', :id, '--memory', box_memory ] vb.customize ['modifyvm', :id, '--clipboard', 'bidirectional'] vb.customize ['modifyvm', :id, '--accelerate3d', 'off'] vb.customize ['modifyvm', :id, '--audio', 'none'] vb.customize ['modifyvm', :id, '--usb', 'off'] end # TODO: detect and abort run if there are vi files # FATAL: Chef::Exceptions::AttributeNotFound: could not find filename for attribute .default.rb.swp in cookbook example # Provision software puts "Provision software for '#{config.vm.box}'" case config_vm_box when /ubuntu|debian/ config.vm.provision 'shell', inline: <<-EOF # create the maven repo mockup REPOSITORY='/home/vagrant/.m2/repository' mkdir -p $REPOSITORY # populate the maven repo mockup with real file to exercise the load # the workspace directory has a small repository to seed the VM sudo cp -R /vagrant/repository/ $REPOSITORY chown -R vagrant:vagrant $REPOSITORY du -s $REPOSITORY # install java directly # NOTE: trusty repos do not have java 1.8 apt-get -qqy update apt-get install -qqy openjdk-7-jdk update-alternatives --set java /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java # NOTE: starting from 2.54 Jenkins requires java 1.8 # TODO: enforce legacy Jenkins in recipe add-apt-repository -y ppa:openjdk-r/ppa apt-get -qqy update apt-get install -qqy openjdk-8-jdk update-alternatives --set java /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java EOF # Use Chef provisioner with Ubuntu # https://www.vagrantup.com/docs/provisioning/chef_solo.html config.vm.provision :chef_solo do |chef| chef.version = '14.10.9' # chef.data_bags_path = 'data_bags' # will require downloading locally - # all stock cookbooks need to be kept in.gitignore chef.add_recipe 'example' chef.log_level = 'info' # TODO: fix error with compiling windows cookbooks which become a dependency of the multi-platform recipe now: # FATAL: ArgumentError: unknown keyword: on_platforms end else # windows # TODO: find and abort provision run if there are temp vi files in cookbooks # FATAL: Chef::Exceptions::AttributeNotFound: could not find filename for attribute .default.rb.swp in cookbook example found_tempfiles = false tempfiles = [] Find.find('cookbooks') do |path| if FileTest.file?(path) if File.basename(path)[0] =~ /^\..*sw.$/ found_tempfiles = true tempfiles += File.basename(path)[0] break else next end end end if found_tempfiles $stderr.puts ( 'Found tempfiles: ' + tempfiles.join(',')) end if config_vm_box_bootstrap config.vm.provision :shell, inline: <<-EOF set-executionpolicy Unrestricted # TODO: Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope. # Due to the override, your shell will retain its current effective execution policy of Bypass. Type "Get-ExecutionPolicy -List" to view # NOTE: when uncommended, leads to an error # Bad HTTP response returned from server. Body(if present): (500). (WinRM::WinRMHTTPTransportError) # run 'bootstrap_legacy.cmd' instead. # enable-psremoting -force EOF if File.exist?('install_net4.ps1') $stderr.puts '(Re)install .Net 4' config.vm.provision :shell, :path => 'install_net4.ps1' end if box_chefdk if File.exist?('install_chocolatey.ps1') $stderr.puts 'Install chocolatey' config.vm.provision :shell, :path => 'install_chocolatey.ps1' end if File.exist?('install_chef.ps1') $stderr.puts 'install puppet and chef using chocolatey' config.vm.provision :shell, :path => 'install_chef.ps1', :args => ['-package_name', 'chefdk', '-package_version', '3.5.13'] # NOTE: Exit code was '1603'. Exit code indicates the following: Generic MSI Error. This is a local environment error, not an issue with a package or the MSI itself - it could mean a pending reboot is necessary prior to install or something else (like the same version is already installed). Please see MSI log if available. If not, try again adding '--install-arguments="'/l*v end end end $stderr.puts# create the maven repo mockup # populate the maven repo mockup with real file to exercise the load # the workspace directory has a small repository to seed the VM appdata = 'APPDATA' allusersprofile = 'ALLUSERSPROFILE' config.vm.provision :shell, inline: <<-EOF $Repository = "${env:#{allusersprofile}}/Jenkins/.m2/repository" # NOTE: double quotes required to prevent error (mkdir: Cannot find drive. A drive with the name '${env' does not exist). if (-not (test-path -path $Repository)) { mkdir $Repository write-host ('Creating {0}' -f $Repository) } copy-item -recurse -force /vagrant/repository $Repository/.. write-host ('Populating {0}' -f $Repository) # https://stackoverflow.com/questions/868264/du-in-powershell # NOTE: verbose function get-diskusage { param( [String]$pathi = "${Repository}" ) $groupedList = Get-ChildItem -Recurse -File $path | Group-Object directoryName | select name,@{name='length'; expression={($_.group | Measure-Object -sum length).sum } } foreach ($dn in $groupedList) { New-Object psobject -Property @{ directoryName=$dn.name; length=($groupedList | where { $_.name -like "$($dn.name)*" } | Measure-Object -Sum length).sum } } } get-diskusage -path $Repository EOF # Use chef provisioner config.vm.provision :chef_solo do |chef| # chef.version = '14.10.9' # NOTE: can not use Chef 14.x on Windows 7 # FATAL: LoadError: Could not open library 'Chef.PowerShell.Wrapper.dll': # https://github.com/chef/chef/issues/8057 suggestion does not help chef.version = '13.10.4' # chef.data_bags_path = 'data_bags' # will require downloading locally - # all chef market cookbook dependencies need to be kept in the '.gitignore' # NOTE: example is now unified. # one still have to comment # 'windows' and 'powershell' dependency cookbook to provision # Linux guest instance node on the Windows host # due to compilation errors it raises chef.add_recipe 'example' chef.log_level = 'info' end end end end
module Smite class Queue < Smite::Object QUEUES = [ { 'name' => 'Conquest', 'id' => 426 }, { 'name' => 'MOTD', 'id' => 434 }, { 'name' => 'Arena', 'id' => 435 }, { 'name' => 'JoustLeague', 'id' => 440 }, { 'name' => 'Assault', 'id' => 445 }, { 'name' => 'Joust3v3', 'id' => 448 }, { 'name' => 'ConquestLeague', 'id' => 451 }, { 'name' => 'MOTD', 'id' => 465 }, { 'name' => 'Clash', 'id' => 466 }, ] def inspect "#<Smite::Queue #{id} #{name}>" end end end
# Documentation: https://docs.brew.sh/Formula-Cookbook # https://rubydoc.brew.sh/Formula # PLEASE REMOVE ALL GENERATED COMMENTS BEFORE SUBMITTING YOUR PULL REQUEST! class TencentMarsXlogUtil < Formula version "0.1.4" desc "腾讯Xlog 日志解码" homepage "https://github.com/0x1306a94/tencent-mars-xlog-rust" url "https://github.com/0x1306a94/tencent-mars-xlog-rust/releases/download/#{TencentMarsXlogUtil.version}/tencent-mars-xlog-util-macos-universal-v#{TencentMarsXlogUtil.version}-binaries.zip" sha256 "6ee9198fe29962becbd1f56208d9cb2b89147d2ee88f3db7492c5f3596107e27" # depends_on "cmake" => :build def install bin.install "tencent-mars-xlog-util" puts <<~EOS \033[32mtencent-mars-xlog-util #{TencentMarsXlogUtil.version}\033[0m 0x1306a94 <0x1306a94@gmail.com> tencent-mars-xlog-util \033[33mUSAGE:\033[0m tencent-mars-xlog-util <SUBCOMMAND> \033[33mOPTIONS:\033[0m \033[32m-h, --help\033[0m Print help information \033[32m-V, --version\033[0m Print version information \033[33mSUBCOMMANDS:\033[0m \033[32mdecode\033[0m Decode Xlog \033[32mgen-key\033[0m Generate the key \033[32mhelp\033[0m Print this message or the help of the given subcommand(s) EOS end test do # `test do` will create, run in and delete a temporary directory. # # This test will fail and we won't accept that! For Homebrew/homebrew-core # this will need to be a test that verifies the functionality of the # software. Run the test with `brew test ytoo`. Options passed # to `brew install` such as `--HEAD` also need to be provided to `brew test`. # # The installed folder is not in the path, so use the entire path to any # executables being tested: `system "#{bin}/program", "do", "something"`. system "false" end end
class SetPlaceDefaultRating < ActiveRecord::Migration def up change_column_default :places, :rating, 0 end def down change_column_default :places, :rating, nil end end
class FileChunk < ApplicationRecord has_attached_file :data belongs_to :chunked_upload_task validates :data, presence: true validates_attachment_content_type :data, content_type: /.+\/.+/ validates :chunked_upload_task, presence: true end
# -*- encoding: utf-8 -*- # stub: opengraph 0.0.4 ruby lib Gem::Specification.new do |s| s.name = "opengraph" s.version = "0.0.4" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.require_paths = ["lib"] s.authors = ["Michael Bleigh"] s.date = "2010-11-04" s.description = "A very simple Ruby library for parsing Open Graph prototocol information from websites. See http://opengraphprotocol.org for more information." s.email = "michael@intridea.com" s.extra_rdoc_files = ["LICENSE", "README.rdoc"] s.files = ["LICENSE", "README.rdoc"] s.homepage = "http://github.com/intridea/opengraph" s.rdoc_options = ["--charset=UTF-8"] s.rubygems_version = "2.2.2" s.summary = "A very simple Ruby library for parsing Open Graph prototocol information from websites." s.installed_by_version = "2.2.2" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<hashie>, [">= 0"]) s.add_runtime_dependency(%q<nokogiri>, ["~> 1.4.0"]) s.add_runtime_dependency(%q<rest-client>, ["~> 1.6.0"]) s.add_development_dependency(%q<rspec>, [">= 1.2.9"]) s.add_development_dependency(%q<webmock>, [">= 0"]) else s.add_dependency(%q<hashie>, [">= 0"]) s.add_dependency(%q<nokogiri>, ["~> 1.4.0"]) s.add_dependency(%q<rest-client>, ["~> 1.6.0"]) s.add_dependency(%q<rspec>, [">= 1.2.9"]) s.add_dependency(%q<webmock>, [">= 0"]) end else s.add_dependency(%q<hashie>, [">= 0"]) s.add_dependency(%q<nokogiri>, ["~> 1.4.0"]) s.add_dependency(%q<rest-client>, ["~> 1.6.0"]) s.add_dependency(%q<rspec>, [">= 1.2.9"]) s.add_dependency(%q<webmock>, [">= 0"]) end end
json.array! @banners do |b| json.id b.id json.url b.image.url json.filename File.basename(b.image.url) end
module MoneyMover module Dwolla class CustomerFundingSourceResource < BaseResource list_filters :removed endpoint_path "/customers/:customer_id/funding-sources", action: [:list, :create] endpoint_path "/funding-sources/:id", action: [:update, :destroy, :find] end end end
class Stop < ActiveRecord::Base has_and_belongs_to_many :buses has_many :sapeadas has_many :centroids end
class BlogsController < ApplicationController before_action :authenticate_user!, only: [:new, :create, :index, :edit, :update, :destroy] before_action :correct_blog_owner, only: [:edit, :update, :destroy] before_action :set_blog, only: [:show, :edit, :update, :destroy] respond_to :json def new @blog = Blog.new end def create @blog = Blog.new(blog_params) if @blog.save notice redirect_to @blog, notice: "ブログが作成.保存されました。" else render 'new', notice: "ブログが作成.保存されませんでした。" end end def show end def index @blogs = @current_user.blogs.order(created_at: :desc).paginate(page: params[:page], per_page: 3) end def edit end def update if @blog.update(blog_params) redirect_to @blog flash[:notice] = "ブログが更新されました。" else render 'edit' end end def destroy @blog.destroy redirect_to blogs_path flash[:notice] = "ブログが削除されました。" end private def set_blog @blog = Blog.find(params[:id]) end def correct_blog_owner @blog = Blog.find_by(id: params[:id]) if @blog.user_id != @current_user.id flash[:notice] = "この記事のアクセス権限が有りません" redirect_to root_url end end def blog_params params.require(:blog).permit(:title, :text, {blogpicture: []}, :user_id) end end
module Avito module API module V1 class Advertisements < Grape::API resource :advertisements do get '/', jbuilder: 'advertisements/index', skip_auth: true do @ads = rom.relations.advertisements.filter(params).to_a end params do requires :title, type: String requires :category, values: Advertisement::CATEGORIES requires :price_cents, type: Integer end post '/', jbuilder: 'advertisements/show' do @ad = rom.command(:advertisements).create.call params.merge(user_id: current_user.id) end post '/:id/deactivate' do @ad = rom.relation(:advertisements).by_id(params[:id]).as(:advertisement).one! fail User::Forbidden unless @ad.can_edit?(current_user) @ad.deactivate! rom.command(:advertisements).update.by_id(@ad.id).call @ad status 202 end end end end end end
#------------------------------------------------------------------------------ # FILE: filter-neon-kube.rb # CONTRIBUTOR: Jeff Lill, Marcus Bowyer # COPYRIGHT: Copyright (c) 2016-2020 by neonFORGE LLC. All rights reserved. # # This Fluentd filter plugin detects container log events forwarded by Kubernetes # and then attempts to extract and parse standard Neon fields from the message. require 'fluent/filter' require 'json' require_relative 'neon-common' module Fluent class NeonKube < Filter include NeonCommon Fluent::Plugin.register_filter('neon-kube', self) def configure(conf) super end def start super end def shutdown super end # Implements the filter. # def filter(tag, time, record) # Detect Kubernetes events. # # Note that I'm explicitly excluding tags like [systemd.**] # because there doesn't seem to be a way to specify an inverse # filter in a Fluentd config. if !record.key?("kubernetes") || tag.start_with?("systemd") return record; # Not from Kubernetes end record["service_host"] = "kubernetes"; # Copy [log] to [message], trimming any whitespace. record["message"] = record["log"].strip; # Try to set [service] to be something useful. pod_name = record["kubernetes"]["pod_name"]; container_name = record["kubernetes"]["container_name"]; if record["kubernetes"].dig("labels", "app").kind_of?(String) service = record["kubernetes"]["labels"]["app"]; elsif record["kubernetes"].dig("labels", "k8s-app").kind_of?(String) service = record["kubernetes"]["labels"]["k8s-app"]; elsif record["kubernetes"].dig("labels", "app_kubernetes_io_name").kind_of?(String) service = record["kubernetes"]["labels"]["app_kubernetes_io_name"]; end if service.nil? if pod_name =~ /(?<service>[A-Za-z0-9\-_.]+[A-Za-z0-9]+)(?<num>\-?\d+)$/i service = $~["service"]; end end if !service.nil? record["service"] = service; end record["container_name"] = container_name record["container_image"] = record.dig("kubernetes", "container_image") rescue nil; record["container_hash"] = record.dig("kubernetes", "container_hash") rescue nil; record["pod_name"] = record.dig("kubernetes", "pod_name") rescue nil; record["pod_ip"] = record.dig("kubernetes", "annotations", "cni_projectcalico_org_podIP") rescue nil; record["kubernetes_namespace"] = record.dig("kubernetes", "namespace_name") rescue nil; container_hash = record.dig("kubernetes", "container_name") rescue nil; # We're going to convert the [container_id] into a short 12-character # field named [cid] and the [cid_full] with the full ID. container_id = record.dig("kubernetes", "docker_id") rescue nil; if !container_id.nil? && container_id.length <= 12 record["cid"] = container_id; else record["cid"] = container_id[0,12]; end record["cid_full"] = container_id; # Same for Pod ID pod_id = record["kubernetes"]["pod_id"]; if !pod_id.nil? && pod_id.length <= 12 record["pid"] = pod_id; else record["pid"] = pod_id[0,12] rescue nil; end record["pid_full"] = pod_id; # Identify messages formatted as JSON and handle them specially. message = record["message"]; if !message.nil? && message.length >= 2 && message[0] == '{' && message[message.length-1] == '}' return extractJson(tag, time, record); end # Attempt to extract standard fields from the message. extractTimestamp(tag, time, record); if !container_name.nil? && container_name == "istio-proxy" message = record["message"]; if message =~ /^(?<match>\[[0-9]*\]\s*\[\s*(?<level>[a-z]*)\s*\])/i match = $~["match"]; level = $~["level"]; level = normalizeLevelTest(level); end if level.nil? level = normalizeLevelTest(message.split(' ')[0]); end if !level.nil? record["level"] = level; record["message"] = message.split(' ', 2)[1]; end elsif !container_name.nil? && container_name.include?("etcd") message = record["message"]; if message =~ /^(?<match>\s?(?<level>[A-Z]))\s\|\s/i match = $~["match"]; level = $~["level"]; level = normalizeLevelTest(level); end if level.nil? level = normalizeLevelTest(message.split(' ')[0]); end if !level.nil? record["level"] = level; record["message"] = message.split('|', 2)[1].strip; end end extractLogLevel(tag, time, record); extractOtherFields(tag, time, record); # Filter out events with an empty [message] or no [json] property if (!record.key?("message") || record["message"].length == 0) && !record.key?("json") return nil; end return record; end end end
require 'spec_helper' require './spec/features/web_helpers' feature '#signup', %q{ As a Maker So that I can post messages on Chitter as me } do scenario 'I want to sign up for Chitter' do expect { signup }.to change { User.count }.by(1) end scenario '&& a successful signup should not throw an error' do signup expect(page).not_to have_content('Sorry') end scenario '&& users cannot choose a username or email that is already taken' do User.create(name: 'foobar', username: 'foo', email: 'foo@bar.com', password: '123') signup expect(page).to have_content('Sorry') end end
# Write a method that takes a String of digits, and returns the appropriate # number as an integer. You may not use any of the methods mentioned above. # I.E * Integer() .to_i def check_which_num(mini_string) case mini_string when '1' then 1 when '2' then 2 when '3' then 3 when '4' then 4 when '5' then 5 when '6' then 6 when '7' then 7 when '8' then 8 when '9' then 9 when '0' then 0 end end def string_to_integer(string) result = string.split('').each_with_object([]) do |n, arr| arr << check_which_num(n) end result.join.to_i end p string_to_integer('4321') == 4321 p string_to_integer('570') == 570 DIGITS = { '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'a' => 10, 'b' => 11, 'c' => 12, 'd' => 13, 'e' => 14, 'f' => 15 } def hexadecimal_to_integer(string) digits = string.downcase.chars.map { |char| DIGITS[char] } value = 0 digits.each { |digit| value = 16 * value + digit } value end p hexadecimal_to_integer('4D9f') == 19_871
class Post < ApplicationRecord has_many :choses, class_name: 'Chose', foreign_key: "posts_id" scope :pager, ->(page: 1, per: 10) { num = page.to_i.positive? ? page.to_i - 1 : 0 limit(per).offset(per * num) } end
require 'test_helper' class Logic::NginxProxyTest < ActionController::TestCase def setup @provider = FactoryBot.create(:provider_account) end def test_generate_proxy_zip assert @provider.generate_proxy_zip end def test_generate_proxy_zip_oauth @provider.services.update_all(backend_version: 'oauth') assert @provider.generate_proxy_zip end def test_deploy_production_apicast default_options = Paperclip::Attachment.default_options Paperclip::Attachment.stubs(default_options: default_options.merge(storage: :s3)) CMS::S3.stubs(:bucket).returns('test-bucket-s3') @provider.proxy_configs = StringIO.new('lua') @provider.proxy_configs_conf = StringIO.new('conf') @provider.save! @provider.proxy_configs.s3_interface.client.stub_responses(:copy_object, ->(request) { assert_equal 'test-bucket-s3', request.params[:bucket] assert_equal ".hosted_proxy/sandbox_proxy_#{@provider.id}.lua", request.params[:key] assert_equal "test-bucket-s3/.sandbox_proxy/sandbox_proxy_#{@provider.id}.lua", request.params[:copy_source] }, ->(request) { assert_equal 'test-bucket-s3', request.params[:bucket] assert_equal ".hosted_proxy_confs/sandbox_proxy_#{@provider.id}.conf", request.params[:key] assert_equal "test-bucket-s3/.sandbox_proxy_confs/sandbox_proxy_#{@provider.id}.conf", request.params[:copy_source] }) assert @provider.deploy_production_apicast end end
# Cookbook Name:: selenium # # Copyright 2013, NetSrv Consulting Ltd. # # 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 imitations under the License. # raise "Unsupported platform, this recipe targets Debian systems" unless node['platform_family'] == "debian" include_recipe "selenium::default" package "opera" do options "--force-yes" action :install end
class MeetingsController < ApplicationController before_action :set_meeting, only: [:show, :edit, :update, :destroy] before_action :authenticate_user! def index @meetings = current_user.meetings end def all_users_meetings @meetings = Meeting.all end def show end def new @meeting = Meeting.new end def edit end def show_calendar @meetings = current_user.meetings @finalMeetings = Array.new @meetings.each do |s| @finalMeetings.push(s) if s.rule == "weekly" interval = s.interval count = 7 while interval != 0 newDate = s.dup newDate.start_time += count.days count+=7 @finalMeetings.push(newDate) interval -= 1 end end if s.rule == "daily" interval = s.interval count = 1 while interval != 0 newDate = s.dup newDate.start_time += count.days count+=1 @finalMeetings.push(newDate) interval -= 1 end end if s.rule == "monthly" interval = s.interval count=30 while interval != 0 newDate = s.dup newDate.start_time += count.days count+=30 @finalMeetings.push(newDate) interval -= 1 end end if s.rule == "annually" interval = s.interval count=365 while interval != 0 newDate = s.dup newDate.start_time += count.days count+=365 @finalMeetings.push(newDate) interval -= 1 end end end end def create @meeting = current_user.meetings.create(meeting_params) respond_to do |format| if @meeting.save format.html { redirect_to @meeting, notice: 'Meeting was successfully created.' } else format.html { render :new } end end end def update respond_to do |format| if @meeting.update(meeting_params) format.html { redirect_to @meeting, notice: 'Meeting was successfully updated.' } else format.html { render :edit } end end end def destroy @meeting.destroy respond_to do |format| format.html { redirect_to meetings_url, notice: 'Meeting was successfully destroyed.' } end end private def set_meeting @meeting = Meeting.find(params[:id]) end def meeting_params params.require(:meeting).permit(:name, :start_time, :rule, :interval) end end
# encoding: utf-8 class ZipFile < ActiveRecord::Base default_scope order: 'id desc' attr_accessible :name,:file,:download mount_uploader :file, FileUploader end
class ChangeCommentAndAttachmentDefaultsOnPosts < ActiveRecord::Migration def self.up change_column_default :posts, :attachment_count, 0 change_column_default :posts, :comment_count, 0 end def self.down change_column_default :posts, :comment_count, "NULL" change_column_default :posts, :attachment_count, "NULL" end end
module ApiPresenter module Parsers # Parses values into array of acceptable association map keys: # * Removes blanks and dups # * Underscores camel-cased keys # * Converts to symbol # # @param values [String, Array<String>, Array<Symbol>] Comma-delimited string or array # # @return [Array<Symbol>] # class ParseIncludeParams def self.call(values) return [] if values.blank? array = values.is_a?(Array) ? values.dup : values.split(',') array.select!(&:present?) array.map! { |value| value.try(:underscore) || value } array.uniq! array.map!(&:to_sym) array end end end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable after_initialize :init has_many :daily_activities, dependent: :destroy has_many :foods, through: :daily_activities has_many :exercises, through: :daily_activities def init self.food_goal = 2000 self.exercise_goal = 600 end end
module Comments module CommentMethods extend ActiveSupport::Concern def self.included(comment_model) comment_model.extend Finders comment_model.scope :in_order, -> { comment_model.order('created_at ASC') } comment_model.scope :recent, -> { comment_model.reorder('created_at DESC') } end def is_comment_type?(type) type.to_s == role.singularize.to_s end module Finders # Helper class method to lookup all comments assigned # to all commentable types for a given user. def find_comments_by_user(user, role = "comments") where(["user_id = ? and role = ?", user.id, role]).order("created_at DESC") end # Helper class method to look up all comments for # commentable class name and commentable id. def find_comments_for_commentable(commentable_str, commentable_id, role = "comments") where(["commentable_type = ? and commentable_id = ? and role = ?", commentable_str, commentable_id, role]).order("created_at DESC") end # Helper class method to look up a commentable object # given the commentable class name and id def find_commentable(commentable_str, commentable_id) model = commentable_str.constantize model.respond_to?(:find_comments_for) ? model.find(commentable_id) : nil end end end end
require "spec_helper" describe Api::TransactionsController, type: :controller do describe "GET #index" do it "should query 2 Transactions" do user = create(:user) login(user) product = create(:product) create_list(:transaction, 2, product_id: product.id, user: user).first get(:index) expect(json.count).to eq 2 end end describe "GET #show" do it "should read 1 Transaction" do user = create(:user) login(user) product = create(:product) transaction = create(:transaction, product_id: product.id, user: user) get( :show, id: transaction.id) expect(json.keys).to include("id") end end describe "POST #create" do before do @user = create(:user) login(@user) @product = create(:product) end context "with valid attributes" do it "should create Transaction" do transaction_attributes = attributes_for(:transaction, product_id: @product.id, user: @user) expect do post( :create, transaction: transaction_attributes) end.to change(Transaction, :count).by(1) end end context "with invalid attributes" do it "should not create Transaction" do transaction_attributes = attributes_for(:transaction, amount: nil, product_id: @product.id, user: @user) expect do post( :create, transaction: transaction_attributes) end.to change(Transaction, :count).by(0) end end end describe "PATCH #update" do before do user = create(:user) product = create(:product) @transaction = create(:transaction, product_id: product.id, user: user) admin = create(:administrator) login(admin) end context "with valid attributes" do it "should update Transaction" do amount = @transaction.amount + rand(1..100) patch( :update, id: @transaction.id, transaction: { amount: amount }) expect(Transaction.find(@transaction.id).amount).to eq(amount) end end context "with invalid attributes" do it "should not update Transaction" do patch( :update, id: @transaction.id, transaction: { amount: nil }) expect(Transaction.find(@transaction.id).amount).to eq(@transaction.amount) end end end describe "DELETE #destroy" do it "should delete Transaction" do user = create(:user) product = create(:product) transaction = create(:transaction, product_id: product.id, user: user) admin = create(:administrator) login(admin) expect do delete( :destroy, id: transaction.id) end.to change(Transaction, :count).by(-1) end end end
Rails.application.routes.draw do # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" root 'pages#index' resources :patients, only: [:show] do end get '/login' => 'sessions#new' post '/login' => 'sessions#create' delete '/logout' => 'sessions#destroy' end
class BankAccount @@no_of_accounts = 0 def initialize set_number @checking = 0 @savings = 0 @interest_rate = 0 end def get_number puts @account_number self end def get_checking puts @checking self end def get_savings puts @savings self end def get_total puts @savings + @checking self end def deposit_checking(amt) @checking += amt self end def deposit_savings(amt) @savings += amt self end def withdraw_checking(amt) if amt < @checking @checking -= amt puts "you have withdrawn #{amt} from checking. #{@checking} remains" else puts "you dont have enuff" end self end def withdraw_savings(amt) if amt < @savings @savings -= amt puts "you have withdrawn #{amt} from savings. #{@savings} remains" else puts "you dont have enuff" end self end def account_information puts "your account number is #{@account_number}. your total money is #{@checking + @savings}. your checking balance is #{@checking} and your savings balance is #{@savings}. interest rate is #{@interest_rate}" self end private def set_number @@no_of_accounts += 1 @account_number = rand(1000..9999) end end myAccount = BankAccount.new myAccount.deposit_savings(1000).deposit_checking(2000).withdraw_savings(50).account_information
class ComponentDashboardSerializer < ActiveModel::Serializer attributes :id, :row, :col, :endpoint, :secret_key, :response_data_location, :refresh_time, :title, :subtitle, :sizeX, :sizeY belongs_to :component end
require 'thor' require 'fileutils' require 'highline' require 'f5_tools' require 'json' require 'utils/cli_utils' module F5_Tools::CLI # 'Define' Subcommand CLI Class. See thor help for descriptions of methods class Define < Thor include F5_Object include F5_Tools::Resolution include F5_Tools::YAMLUtils include CLI_Utils desc 'facility <facility>', 'Define a facility in local configuration' def facility(fac_name) puts 'Creating facility:'.colorize(:white).on_black + ' ' + fac_name FileUtils.mkdir_p "defs/facilities/#{fac_name}/net_devices" ['endpoints.yaml', 'segments.yaml', 'nodes.yaml', '_vars.yaml'].each do |fName| FileUtils.touch "defs/facilities/#{fac_name}/#{fName}" end cli = HighLine.new internal = cli.ask 'Facility internal CIDR block?' external = cli.ask 'Facility external endpoint? (For ipsec)' modify_yaml FACILITIES_YAML do |data| data[fac_name] = {} data[fac_name]['internal'] = internal data[fac_name]['external'] = external data end created_str = 'Defined facility: '.colorize(:green).on_black + fac_name print_lined created_str puts 'Facilities:' puts listify(facilities_list) end desc 'device <device>', 'Defines a device in local configuration' def device(device) puts 'Creating net_device:'.colorize(:white).on_black + ' ' + device yaml_path = construct_device_path device FileUtils.mkdir_p 'defs/device_templates' FileUtils.touch yaml_path cli = HighLine.new hostname = cli.ask 'F5 hostname?' modify_yaml yaml_path do |_data| { 'hostname' => hostname } end created_str = 'Defined device: '.colorize(:green).on_black + device.colorize(:blue) print_lined created_str # puts "Devices in #{fac_name.colorize(:blue)}:" # puts listify(devices_list(fac_name)) end option :facility, aliases: '-f' desc 'segment <internal/external/global> <name> <cidr_block>', 'Defines a segment in a facility' def segment(loc, name, cidr) case loc.downcase when 'internal', 'external' fac_name = options.fetch :facility, HighLine.new.ask('Facility?') init_facility fac_name, nil yaml_path = construct_yaml_path(F5_Tools::YAMLUtils::FACILITY_PATH.dup + 'segments.yaml', options[:facility]) loc = loc.downcase data = load_or_create_yaml(yaml_path) data[loc] = [] unless data[loc] data[loc].push('name' => name, loc == 'internal' ? 'size' : 'cidr' => cidr) when 'global' yaml_path = 'defs/segments.yaml' data = load_or_create_yaml(yaml_path) data = [] unless data data.push('name' => name, 'cidr' => cidr) else raise 'Invalid location. Choices: internal, external, global' end File.open(yaml_path, 'w') { |f| f.write data.to_yaml } end desc 'endpoint <facility> <name> <addr>', 'Defines an endpoint in a facility' def endpoint(fac_name, name, addr) # init_facility fac_name, nil yaml_path = construct_yaml_path(FACILITY_ENDPOINTS_YAML, fac_name) data = load_or_create_yaml yaml_path data = [] if !data || data == {} data.push('name' => name, 'addr' => addr) File.open(yaml_path, 'w') { |f| f.write data.to_yaml } puts "Defined endpoint '#{name} => #{addr}' in #{fac_name}".colorize(:green) end desc 'port_symbol <name> <port>', 'Defines a named port symbol' def port_symbol(name, port) modify_yaml(F5_Tools::YAMLUtils::PORT_SYMBOL_YAML) do |data| # Overwrite default datatype (if port_symbols.yaml is empty) data = [] if data == {} data.push('name' => name, 'port' => port.to_i) end puts "Defined port symbol '#{name} => #{port}'".colorize(:green) end end end
require 'spec_helper' describe Immutable::Hash do [:to_hash, :to_h].each do |method| describe "##{method}" do it 'converts an empty Immutable::Hash to an empty Ruby Hash' do H.empty.send(method).should eql({}) end it 'converts a non-empty Immutable::Hash to a Hash with the same keys and values' do H[a: 1, b: 2].send(method).should eql({a: 1, b: 2}) end it "doesn't modify the receiver" do hash = H[a: 1, b: 2] hash.send(method) hash.should eql(H[a: 1, b: 2]) end end end end
require 'rest-client' require 'json' require 'pry' def get_character_movies_from_api(character_name) response_string = RestClient.get("http://www.swapi.co/api/people/") response_hash = JSON.parse(response_string)["results"] film_urls = nil film_array = [] response_hash.each_with_index do |char, index| if char["name"].downcase.include?(character_name) film_urls = response_hash[index]["films"] end end if film_urls film_urls.each do |url| movie_response_string = RestClient.get(url) movie_response_hash = JSON.parse(movie_response_string) film_array << movie_response_hash end end film_array end def print_movies(films) puts "Films homeboy/girl was in: " # binding.pry films.each do |film| puts "#{film["title"]}" end end def show_character_movies(character) films = get_character_movies_from_api(character) if films != [] print_movies(films) else puts 'no movies' end end ## BONUS # that `get_character_movies_from_api` method is probably pretty long. Does it do more than one job? # can you split it up into helper methods?
require 'spec_helper' describe SearchPresenter, :type => :view do let(:user) { users(:owner) } before do reindex_solr_fixtures stub(ActiveRecord::Base).current_user { user } end describe "#to_hash" do context "searching without workspace" do before do search = Search.new(user, :query => 'searchquery') VCR.use_cassette('search_solr_query_all_types_as_owner') do search.search end @presenter = SearchPresenter.new(search, view) @hash = @presenter.to_hash end it "includes the right user keys" do @hash.should have_key(:users) user_hash = @hash[:users] user_hash.should have_key(:numFound) user_hash.should have_key(:results) user_hash[:results][0].should have_key(:highlighted_attributes) user_hash[:results][0][:entity_type].should == 'user' end it "includes the right instance keys" do @hash.should have_key(:instances) instance_hash = @hash[:instances] instance_hash.should have_key(:numFound) instance_hash.should have_key(:results) instance_types = instance_hash[:results].map {|result| result[:entity_type]}.uniq instance_types.should =~ ['greenplum_instance', 'hadoop_instance', 'gnip_instance'] instance_hash[:results].each do |result| result.should have_key(:highlighted_attributes) end end it "includes the right workspace keys" do @hash.should have_key(:workspaces) workspaces_hash = @hash[:workspaces] workspaces_hash.should have_key(:numFound) workspaces_hash.should have_key(:results) workspaces_hash[:results][0].should have_key(:highlighted_attributes) workspaces_hash[:results][0][:entity_type].should == 'workspace' end it "includes the right workfile keys" do @hash.should have_key(:workfiles) workfile_hash = @hash[:workfiles] workfile_hash.should have_key(:numFound) workfile_hash.should have_key(:results) workfile_hash[:results][0].should have_key(:highlighted_attributes) workfile_hash[:results][0].should have_key(:version_info) workfile_hash[:results][0][:entity_type].should == 'workfile' end it "includes the comments" do gpdb_instance_hash = @hash[:instances] gpdb_instance_result = gpdb_instance_hash[:results][0] gpdb_instance_result.should have_key(:comments) gpdb_instance_result[:comments].length.should == 1 gpdb_instance_result[:comments][0][:highlighted_attributes][:body][0].should == "i love <em>searchquery</em>" end it "includes the right dataset keys" do @hash.should have_key(:datasets) datasets_hash = @hash[:datasets] datasets_hash.should have_key(:numFound) datasets_hash.should have_key(:results) datasets_hash[:results][0].should have_key(:highlighted_attributes) datasets_hash[:results][0][:highlighted_attributes].should have_key(:object_name) #datasets_hash[:results][0][:schema].should have_key(:highlighted_attributes) #datasets_hash[:results][0][:schema][:highlighted_attributes].should have_key(:name) datasets_hash[:results][0][:columns][0].should have_key(:highlighted_attributes) datasets_hash[:results][0][:columns][0][:highlighted_attributes].should have_key(:body) #datasets_hash[:results][0][:schema][:database].should have_key(:highlighted_attributes) #datasets_hash[:results][0][:schema][:database][:highlighted_attributes].should have_key(:name) datasets_hash[:results][0][:highlighted_attributes].should_not have_key(:name) datasets_hash[:results][0][:highlighted_attributes].should_not have_key(:database_name) datasets_hash[:results][0][:highlighted_attributes].should_not have_key(:schema_name) datasets_hash[:results][0][:highlighted_attributes].should_not have_key(:column_name) datasets_hash[:results][0][:entity_type].should == 'dataset' end it "includes the hdfs entries" do @hash.should have_key(:hdfs) hdfs_hash = @hash[:hdfs] hdfs_hash.should have_key(:numFound) hdfs_hash.should have_key(:results) first_result = hdfs_hash[:results][0] first_result.should have_key(:path) first_result.should have_key(:name) first_result.should have_key(:ancestors) first_result.should have_key(:highlighted_attributes) first_result[:entity_type].should == 'hdfs_file' end it "includes note attachments" do @hash.should have_key(:attachment) attachments_hash = @hash[:attachment] attachments_hash.should have_key(:numFound) attachments_hash.should have_key(:results) attachments_hash[:results][0][:highlighted_attributes].should have_key(:name) attachments_hash[:results][0][:entity_type].should == 'attachment' end it "does not include the this_workspace key" do @hash.should_not have_key(:this_workspace) end end context "when workspace_id is set on the search" do let(:workspace) { workspaces(:search_public) } before do search = Search.new(user, :query => 'searchquery', :workspace_id => workspace.id) VCR.use_cassette('search_solr_query_all_types_with_workspace_as_owner') do search.models end @presenter = SearchPresenter.new(search, view) @hash = @presenter.to_hash end it "includes the right this_workspace keys" do @hash.should have_key(:this_workspace) this_workspace_hash = @hash[:this_workspace] this_workspace_hash.should have_key(:numFound) this_workspace_hash.should have_key(:results) end it "puts the highlighted schema attributes on the schema" do dataset_hash = @hash[:this_workspace][:results].find { |entry| entry[:entity_type] == 'dataset' } dataset_hash[:schema][:highlighted_attributes][:name][0].should == "<em>searchquery</em>_schema" dataset_hash[:schema][:database][:highlighted_attributes][:name][0].should == "<em>searchquery</em>_database" dataset_hash.should have_key(:workspace) end end end end
# frozen_string_literal: true class PaperTrailTestWithCustomAssociation < ActiveRecord::Base self.table_name = :paper_trail_tests has_paper_trail versions: {class_name: 'Trail'} end
require 'rails_helper' RSpec.describe Project do describe "initialization" do let(:project){Project.new} let(:task){Task.new} it "considers a project with no tasks to be done" do expect(project.done?).to be_truthy end it "knows that a project with an incomplete task is not done" do project.tasks << task expect(project.done?).to be_falsy end it "maskts a project done if its tasks are done" do project.tasks << task task.mark_completed expect(project).to be_done end it "estimates a blank project" do expect(project.completed_velocity).to eq(0) expect(project.current_rate).to eq(0) expect(project.projected_days_remaining.nan?).to be_truthy expect(project).not_to be_on_schedule end end describe "estimate" do let(:project){Project.new} let(:newly_done) {Task.new(size:3,completed_at: 1.day.ago)} let(:old_done){Task.new(size:2,completed_at: 6.months.ago)} let(:small_not_done){Task.new(size:1)} let(:large_not_done){Task.new(size:4)} before(:example) do project.tasks =[newly_done,old_done,small_not_done,large_not_done] end it "knows its velocity" do expect(project.completed_velocity).to eq(3) end it "knows its rate" do expect(project.current_rate).to eq(1.0/7) end it "knows its projected time remaining" do expect(project.projected_days_remaining).to eq(35) end it "knows if it is on schdule" do project.due_date=1.week.from_now expect(project).not_to be_on_schedule project.due_date = 6.months.from_now expect(project).to be_on_schedule end end end
require_relative 'game_state' require_relative 'state_main_game' require 'gosu' require_relative '../button' require_relative '../input' class StateMenu < GameState def initialize(state_stack) @state_stack = state_stack @menu_font = Gosu::Font.new(50) @frog_button = Button.new($window_x/2-110, $window_y/2, Gosu::Image.new('../assets/images/button_frog.png', :tileable => false, :retro => true)) @vehicle_button = Button.new($window_x/2, $window_y/2, Gosu::Image.new('../assets/images/button_vehicle.png', :tileable => false, :retro => true)) @single_player_button = Button.new($window_x/2-200, $window_y/2+100, Gosu::Image.new('../assets/images/button_single-player.png', :tileable => false, :retro => true)) @multi_player_button = Button.new($window_x/2, $window_y/2+100, Gosu::Image.new('../assets/images/button_multi-player.png', :tileable => false, :retro => true)) @start_button = Button.new($window_x/2-100, $window_y/2+300, Gosu::Image.new('../assets/images/button_start.png', :tileable => false, :retro => true)) @isFrog = true @isMultiplayer = false end def update(dt) if @frog_button.is_pressed(Input.mouse_x, Input.mouse_y) @isFrog = true elsif @vehicle_button.is_pressed(Input.mouse_x, Input.mouse_y) @isFrog = false elsif @single_player_button.is_pressed(Input.mouse_x, Input.mouse_y) @isMultiplayer = false elsif @multi_player_button.is_pressed(Input.mouse_x, Input.mouse_y) @isMultiplayer = true elsif @start_button.is_pressed(Input.mouse_x, Input.mouse_y) @state_stack.push StateMainGame.new(@state_stack, @isFrog, @isMultiplayer) end end def draw menu_font_text = "REGGORF" menu_font_x_coordinate = $window_x/2 -100 menu_font_y_coordinate = 100 menu_font_z_coordinate = 0 @menu_font.draw( menu_font_text, menu_font_x_coordinate, menu_font_y_coordinate, menu_font_z_coordinate ) @frog_button.draw @vehicle_button.draw @single_player_button.draw @multi_player_button.draw @start_button.draw end end
require 'rails_helper' RSpec.describe TravelPlan::Form, type: :model do let(:account) { Account.new } let(:form) { new_form } subject { form } def new_form described_class.new(account.travel_plans.new) end # Returns the errors object for the given attributes. For convenience, if # your attributes hash only has one key, it will return the errors for that # specific key rather than the whole error object. def errors_for(attrs = {}) form = new_form form.validate(attrs) if attrs.keys.length == 1 form.errors[attrs.keys.first] else form.errors end end describe 'prepopulate!' do let(:form) { described_class.new(travel_plan) } context 'when TP is being edited' do let(:travel_plan) { create_travel_plan(depart_on: '2020-01-02', return_on: '2025-12-05') } let(:flight) { travel_plan.flights[0] } before { form.prepopulate! } it 'fills "from" and "to" with the airport info' do expect(form.from).to eq flight.from.full_name expect(form.to).to eq flight.to.full_name end end context 'when TP is new' do let(:travel_plan) { TravelPlan.new } it 'leaves from/to and dates blank' do expect(form.from).to be nil expect(form.to).to be nil end end end describe 'validations' do %w[from to].each do |dest| describe dest do it 'fails gracefully when blank or invalid' do expect(errors_for(dest => ' ')).to include "can't be blank" [ 'ioajwera', 'jaoiwerj a (AA)', 'iajower (AAAA)', 'iajower (AAAA', ].each do |val| expect(errors_for(dest => val)).to include 'is invalid' end end end end it { is_expected.to validate_presence_of(:depart_on) } it { is_expected.to validate_presence_of(:no_of_passengers) } describe "#no_of_passengers" do it 'must be >= 1, <= 20' do def errors_for_no(no) errors_for(no_of_passengers: no) end expect(errors_for_no(0)).to eq ['must be greater than or equal to 1'] expect(errors_for_no(1)).to be_empty expect(errors_for_no(20)).to be_empty expect(errors_for_no(21)).to eq ['must be less than or equal to 20'] end end it 'further_information is <= 500 chars' do def errors_for_length(l) errors_for(further_information: ('a' * l)) end expect(errors_for_length(500)).to be_empty expect(errors_for_length(501)).to eq ['is too long (maximum is 500 characters)'] end specify "depart_on must be present and not in the past" do def errors_for_date(date) errors_for(depart_on: date) end expect(errors_for_date(nil)).to eq ["can't be blank"] form.depart_on = Time.zone.yesterday expect(errors_for_date(Time.zone.yesterday)).to eq ["can't be in the past"] expect(errors_for_date(Time.zone.today)).to be_empty end specify 'return_on must be blank when type is one-way' do form.type = 'one_way' expect(form).to validate_absence_of(:return_on) end context "when type is round-trip" do specify "return date must be present and not in the past" do def errors_for_date(date) errors_for(return_on: date, type: 'round_trip')[:return_on] end expect(errors_for_date(nil)).to include "can't be blank" expect(errors_for_date(Time.zone.yesterday)).to include "can't be in the past" expect(errors_for_date(Time.zone.today)).to be_empty end specify "return date must be >= departure" do def errors_for_dates(dep, ret) errors_for(depart_on: dep, return_on: ret, type: 'round_trip')[:return_on] end tomorrow = Time.zone.tomorrow today = Time.zone.today expect(errors_for_dates(tomorrow, today)).to eq ["can't be earlier than departure date"] expect(errors_for_dates(tomorrow, tomorrow)).to be_empty end end end describe 'saving' do let(:account) { create_account(:onboarded) } let(:airport_0) { create(:airport) } let(:airport_1) { create(:airport) } let(:account) { create_account(:onboarded) } example 'creating a new travel plan' do form = described_class.new(account.travel_plans.new) expect( form.validate( from: "#{airport_0.name} (#{airport_0.code})", to: "#{airport_1.name} (#{airport_1.code})", type: 'round_trip', no_of_passengers: 5, accepts_economy: true, accepts_premium_economy: true, accepts_business_class: true, accepts_first_class: true, depart_on: '05/08/2025', return_on: '02/03/2026', further_information: 'blah blah blah', ), ).to be true expect(form.save).to be true tp = form.model expect(tp.flights[0].from).to eq airport_0 expect(tp.flights[0].to).to eq airport_1 expect(tp.type).to eq 'round_trip' expect(tp.no_of_passengers).to eq 5 expect(tp.accepts_economy).to be true expect(tp.accepts_premium_economy).to be true expect(tp.accepts_business_class).to be true expect(tp.accepts_first_class).to be true expect(tp.depart_on).to eq Date.new(2025, 5, 8) expect(tp.return_on).to eq Date.new(2026, 2, 3) expect(tp.further_information).to eq 'blah blah blah' end example 'updating a travel plan' do plan = create_travel_plan( accepts_business_class: true, accepts_economy: true, accepts_first_class: true, accepts_premium_economy: true, account: account, depart_on: '05/08/2025', from: airport_0, further_information: 'blah blah blah', no_of_passengers: 5, return_on: '02/03/2026', to: airport_1, type: 'round_trip', ) form = described_class.new(plan) expect( form.validate( from: "#{airport_1.name} (#{airport_1.code})", to: "#{airport_0.name} (#{airport_0.code})", type: 'round_trip', no_of_passengers: 3, accepts_economy: false, accepts_premium_economy: false, accepts_business_class: false, accepts_first_class: false, depart_on: '05/08/2023', return_on: '02/03/2024', further_information: 'yeah yeah yeah', ), ).to be true expect(form.save).to be true plan.reload expect(plan.flights[0].from).to eq airport_1 expect(plan.flights[0].to).to eq airport_0 expect(plan.type).to eq 'round_trip' expect(plan.no_of_passengers).to eq 3 expect(plan.accepts_economy).to be false expect(plan.accepts_premium_economy).to be false expect(plan.accepts_business_class).to be false expect(plan.accepts_first_class).to be false expect(plan.depart_on).to eq Date.new(2023, 5, 8) expect(plan.return_on).to eq Date.new(2024, 2, 3) expect(plan.further_information).to eq 'yeah yeah yeah' end end end
Vagrant.configure("2") do |config| config.vm.provider "virtualbox" do |v| v.memory = 2048 v.cpus = 1 end config.vm.define "server1" do |server1| server1.vm.hostname = "server1" server1.vm.box = "ubuntu/bionic64" server1.vm.network "private_network", ip: "192.168.60.50" server1.vm.network "forwarded_port", guest: 27017, host: 27017 # Mongodb server1.vm.network "forwarded_port", guest: 9092, host: 19092 # Kafka server1.vm.network "forwarded_port", guest: 2181, host: 12181 # Zookeeper 1 client port server1.vm.network "forwarded_port", guest: 2182, host: 12182 # Zookeeper 2 client port server1.vm.network "forwarded_port", guest: 2888, host: 12888 # Zookeeper 1 port to connect to other peers server1.vm.network "forwarded_port", guest: 2889, host: 12889 # Zookeeper 2 port to connect to other peers server1.vm.network "forwarded_port", guest: 3888, host: 13888 # Zookeeper 1 port for leader election server1.vm.network "forwarded_port", guest: 3889, host: 13889 # Zookeeper 2 port for leader election server1.vm.provision "shell", path: "mongodb1/bootstrap.sh", run: "always" server1.vm.provision "shell", path: "kafka1/bootstrap.sh", run: "always" server1.trigger.before "halt" do |trigger| trigger.warn = "Shutting down Kafka/Zookeeper" trigger.run_remote = {path: "kafka-common/shutdown.sh"} end end config.vm.define "server2" do |server2| server2.vm.hostname = "server2" server2.vm.box = "ubuntu/bionic64" server2.vm.network "private_network", ip: "192.168.60.51" server2.vm.network "forwarded_port", guest: 27017, host: 27018 # Mongodb server2.vm.network "forwarded_port", guest: 9092, host: 29092 # Kafka server2.vm.network "forwarded_port", guest: 2181, host: 22181 # Zookeeper client port server2.vm.network "forwarded_port", guest: 2888, host: 22888 # Zookeeper port to connect to other peers server2.vm.network "forwarded_port", guest: 3888, host: 23888 # Zookeeper port for leader election server2.vm.provision "shell", path: "mongodb2/bootstrap.sh", run: "always" server2.vm.provision "shell", path: "mongodb-common/setup-rc.sh", run: "always" server2.vm.provision "shell", path: "mongodb-common/create_db.sh", run: "always" server2.vm.provision "shell", path: "kafka2/bootstrap.sh", run: "always" server2.vm.provision "shell", path: "kafka-common/create_topics.sh", run: "always" server2.trigger.before "halt" do |trigger| trigger.warn = "Shutting down Kafka/Zookeeper" trigger.run_remote = {path: "kafka-common/shutdown.sh"} end end end
module NoMethodErrorSpecs class NoMethodErrorA; end class NoMethodErrorB; end class NoMethodErrorC; protected def a_protected_method;end private def a_private_method; end end class NoMethodErrorD; end end module ExceptionSpecs class Exceptional < Exception; end class Backtrace def self.backtrace begin raise rescue RuntimeError => e e.backtrace end end end class UnExceptional < Exception def backtrace nil end def message nil end end class ConstructorException < Exception def initialize end end class InitializedException < Exception def initialize ScratchPad.record :initialized_exception end end def self.exception_from_ensure_block_with_rescue_clauses begin raise "some message" ensure ScratchPad.record $!.backtrace end end def self.record_exception_from_ensure_block_with_rescue_clauses begin exception_from_ensure_block_with_rescue_clauses rescue end end end
class Ride < ActiveRecord::Base # write associations here belongs_to :attraction belongs_to :user def take_ride user = self.user attraction = self.attraction if too_short?(user, attraction) || too_broke?(user, attraction) return "Sorry. You do not have enough tickets to ride the #{attraction.name}." if !too_short?(user, attraction) return "Sorry. You are not tall enough to ride the #{attraction.name}." if !too_broke?(user, attraction) "Sorry. You do not have enough tickets to ride the #{attraction.name}. You are not tall enough to ride the #{attraction.name}." else update_user(user, attraction) "Thanks for riding the #{attraction.name}!" end end private def too_short?(user, attraction) user.height < attraction.min_height end def too_broke?(user, attraction) user.tickets < attraction.tickets end def update_user(user, attraction) user.tickets -= attraction.tickets user.nausea += attraction.nausea_rating user.happiness += attraction.happiness_rating user.save end end
class Maze START = 's' GOAL = 'g' PATH = '.' WALL = 'X' WALL_INPUT = '1' PATH_INPUT = '0' def initialize(grids) @grids = grids.map { |row| row.map { |col| convert_grid_value(col) } } @num_rows = @grids.size @num_cols = @grids.first.size @grids = @grids.map { |row| [WALL] + row + [WALL] } @grids.unshift([WALL] * (@num_cols + 2)) @grids.push( [WALL] * (@num_cols + 2)) end MESSAGE_WHEN_FAIL = 'Fail' def shortest_path start_coordinates = locate(START) raise ArgumentError, "No start found" if start_coordinates.empty? raise ArgumentError, "Multiple starts" if start_coordinates.size > 1 marked_coordinates = start_coordinates is_goal_found = false distance = 0 loop do next_coordinates = [] marked_coordinates.each do |i_col, i_row| coordinates = mark_distance(i_col, i_row) if coordinates == GOAL is_goal_found = true break end next_coordinates.concat(coordinates) end distance += 1 break if is_goal_found || next_coordinates.empty? marked_coordinates = next_coordinates end is_goal_found ? distance : MESSAGE_WHEN_FAIL end def to_s @grids.map { |row| row.join }.join("\n") end private def mark_distance(i_col, i_row) origin = @grids[i_row][i_col] if origin == GOAL || origin == WALL || origin == PATH raise RuntimeError, "Illegal mark_distance() call with '#{origin}' @(#{i_col}, #{i_row})" end marked_coordinates = [] distance = origin == START ? 1 : origin + 1 [[0, -1], [0, 1], [-1, 0], [1, 0]].each do |d_col, d_row| _i_col = i_col + d_col _i_row = i_row + d_row adjacent = @grids[_i_row][_i_col] if adjacent == GOAL return GOAL elsif adjacent == PATH @grids[_i_row][_i_col] = distance marked_coordinates << [_i_col, _i_row] end end marked_coordinates end def locate(value) retval = [] 1.upto(@num_rows) do |i_row| 1.upto(@num_cols) do |i_col| if @grids[i_row][i_col] == value retval << [i_col, i_row] end end end retval end def convert_grid_value(value) if value == WALL_INPUT WALL elsif value == PATH_INPUT PATH else value end end end if __FILE__ == $0 num_cols, num_rows = gets.split.map(&:to_i) grids = Array.new(num_rows) num_rows.times do |index_row| grids[index_row] = gets.chomp.split end maze = Maze.new(grids) puts maze.shortest_path end