text
stringlengths
10
2.61M
class EventEvent < DomainModel attr_accessor :starts_at, :ends_at, :ends_on, :ends_time include ModelExtension::HandlerExtension belongs_to :parent, :class_name => 'EventEvent', :foreign_key => :parent_id has_many :children, :class_name => 'EventEvent', :foreign_key => :parent_id, :order => 'event_at', :dependent => :destroy belongs_to :event_type belongs_to :owner, :polymorphic => true has_end_user :end_user_id has_many :event_bookings, :dependent => :destroy has_many :event_repeats, :dependent => :delete_all handler :handler, :event, :type before_validation_on_create :set_defaults before_validation :set_event_at before_validation :set_permalink validates_presence_of :event_type_id validates_presence_of :permalink validates_presence_of :name validates_presence_of :event_on validates_numericality_of :start_time, :greater_than_or_equal_to => 0, :allow_nil => true validates_numericality_of :duration, :greater_than_or_equal_to => 0 validates_uniqueness_of :permalink validate :validate_event_times validate :validate_custom_content after_save :update_custom_content after_save :update_spaces before_create { |event| event.total_allowed ||= 1000 } named_scope :published, where(:published => true) named_scope :directory, where(:directory => true) # wether or not to display the event in the list paragraph def self.for_owner(owner,include_others=false) owner_type,owner_id = case owner when DomainModel [ owner.class.to_s, owner.id ] when Array [ owner[0].to_s, owner[1] ] else return self end if include_others self.where("((owner_type = ? and owner_id = ?) OR owner_type is NULL)",owner_type,owner_id) else self.where(:owner_type => owner_type, :owner_id => owner_id) end end def self.calculate_start_time_options options = [['All day', nil]] period = 15 (0..(1440/period - 1)).each do |idx| minutes = idx * period hour = minutes / 60 meridiem = 'am' if hour >= 12 meridiem = 'pm' hour -= 12 if hour > 12 elsif hour == 0 hour = 12 end m = minutes % 60 options << [sprintf("%02d:%02d %s", hour, m, meridiem), minutes] end options end @@start_time_options = self.calculate_start_time_options has_options :start_time, @@start_time_options def self.calculate_duration_options options = [] period = 15 (1..(360/period - 1)).each do |idx| minutes = (idx * period) % 60 hour = (idx * period) / 60 options << [sprintf("%02d:%02d hours/mins", hour, minutes), idx * period] end (6..23).each do |idx| options << ["#{idx} hours", idx*60] end options << ["1 day", 1440] (2..6).each do |idx| options << ["#{idx} days", idx*1440] end options << ["1 week", 10080] (2..4).each do |idx| options << ["#{idx} weeks", idx*10080] end options end @@duration_options = self.calculate_duration_options has_options :duration, @@duration_options def all_day_event? self.start_time.nil? end def set_defaults if self.parent self.event_type_id ||= self.parent.event_type_id self.published ||= self.parent.published self.owner_type ||= self.parent.owner_type self.owner_id ||= self.parent.owner_id end self.published ||= false self.duration ||= 0 self.permalink = DomainModel.generate_hash if self.permalink.blank? self.type_handler = self.event_type.type_handler if self.event_type true end def generate_permalink return self.permalink unless self.permalink.blank? && self.event_on && self.name base_url = self.event_on.strftime("%Y-%m-%d") + '-' + SiteNode.generate_node_path(self.name) test_url = base_url cnt = 2 while(EventEvent.where(:permalink => test_url).first) do test_url = "#{base_url}-#{cnt}" cnt += 1 end test_url end def set_permalink self.permalink = self.generate_permalink end def set_event_at if @ends_on && @ends_time @ends_at = @ends_on + @ends_time.to_i.minutes if self.all_day_event? @ends_at = @ends_at.at_beginning_of_day @ends_at += 1.day unless @starts_at end end if @starts_at if self.all_day_event? # all day event @starts_at = @starts_at.at_beginning_of_day @ends_at = (@ends_at || (@starts_at + self.duration.to_i.minutes)).at_beginning_of_day + 1.day end self.event_at = @starts_at @starts_at = nil self.event_on = self.event_at self.start_time = (self.event_at.to_i - self.event_at.at_midnight.to_i) / 60 if self.start_time else self.event_at = self.event_on + self.start_time.to_i.minutes if self.event_on end if @ends_at self.duration = (@ends_at.to_i - self.event_at.to_i) / 60 @ends_at = nil elsif self.all_day_event? self.duration = 1440 end end def starts_at=(time) @starts_at = begin case time when Integer Time.at(time) when String Time.parse(time) when Time time end end end def ends_at=(time) @ends_at = begin case time when Integer Time.at(time) when String Time.parse(time) when Time time end end end def ends_at return @ends_at if @ends_at return nil unless self.event_at if self.start_time self.event_at + self.duration.to_i.minutes else # all day event self.event_at + self.duration.to_i.minutes - 1.day end end def as_json(opts={}) data = { :event_id => self.id, :title => self.published ? self.name : "* #{self.name}", :start => self.event_at, :allDay => self.start_time ? false : true, :end => self.ends_at, :parent_id => self.parent_id } data[:url] = opts[:event_node].link(self.permalink) if opts[:event_node] data end def move(days, minutes, all_day) @starts_at = self.event_at + days.days + minutes.minutes if self.all_day_event? && all_day == false && self.duration == 1440 @ends_at = @starts_at + 2.hours else @ends_at = self.ends_at + days.days + minutes.minutes end self.start_time = all_day ? nil : 0 self.save end def resize(days, minutes) @ends_at = self.ends_at + days.days + minutes.minutes @ends_at += 1.day if self.all_day_event? self.save end def ends_on self.ends_at end def ends_on=(time) @ends_on = begin case time when Integer Time.at(time).at_beginning_of_day when String Time.parse(time).at_beginning_of_day when Time time.at_beginning_of_day end end end def ends_time if self.ends_at (self.ends_at.to_i - self.ends_at.at_midnight.to_i) / 60 else self.start_time end end def ends_time=(minutes) @ends_time = minutes.to_i end def ended? return false unless self.ends_at time = self.ends_at time += 1.day if self.all_day_event? time <= Time.now end def started? self.event_at && self.event_at > Time.now end def validate_event_times if self.duration.to_i < 0 || (self.ends_at && self.event_at && self.event_at > self.ends_at) self.errors.add(:event_on, 'is invalid') self.errors.add(:start_time, 'is invalid') self.errors.add(:ends_on, 'is invalid') self.errors.add(:ends_time, 'is invalid') self.errors.add(:ends_at, 'is invalid') end end def content_model self.event_type.content_model if self.event_type end def relational_field self.event_type.relational_field if self.event_type end def content_data return nil unless self.content_model && self.relational_field return @content_data if @content_data @content_data = self.content_model.content_model.where(self.relational_field.field => self.id).first unless self.new_record? @content_data ||= self.content_model.content_model.new self.relational_field.field => self.id end def content_data=(hsh) self.content_data.attributes = hsh if self.content_data end def validate_custom_content if self.content_data self.errors.add(:content_data, 'is invalid') unless self.content_data.valid? end end def update_custom_content self.content_data.save if self.content_data end def type_handler return self[:type_handler] if self[:type_handler] self[:type_handler] = self.event_type.type_handler if self.event_type self[:type_handler] end def get_field(fld) return self[fld] unless self[fld].blank? self.parent.send(fld) if self.parent end %w(name description address address_2 city state zip lon lat image_id).each do |fld| self.send(:define_method, fld) do get_field fld end end def attendance @attendance ||= self.event_bookings.includes(:end_user).order('responded DESC, attending DESC').all end def event_month @event_month ||= self.event_at.at_beginning_of_month end def can_book? self.spaces_left > 0 end def add_space(quantity) quantity = quantity.to_i affected_rows = self.connection.update "UPDATE event_events SET spaces_left = spaces_left + #{quantity}, bookings = bookings - #{quantity} WHERE id = #{self.id}" return false unless affected_rows == 1 self.spaces_left += quantity self.bookings -= quantity true end def remove_space(quantity) quantity = quantity.to_i affected_rows = self.connection.update "UPDATE event_events SET spaces_left = spaces_left - #{quantity}, bookings = bookings + #{quantity} WHERE id = #{self.id} AND (spaces_left - #{quantity}) >= 0" return false unless affected_rows == 1 self.spaces_left -= quantity self.bookings += quantity true end def total_allowed=(amount) amount = amount.to_i @total_allowed_changed = amount - self[:total_allowed].to_i self[:total_allowed] = amount end def update_spaces return if @total_allowed_changed.to_i == 0 self.connection.update "UPDATE event_events SET spaces_left = spaces_left + #{@total_allowed_changed} WHERE id = #{self.id}" end def location [self.address, self.address_2, "#{self.city}, #{self.state} #{self.zip}"].reject(&:blank?).map(&:strip).compact.join(', ') end end
class Admin::BagesController < Admin::BaseController before_action :find_bage, only: %i[destroy edit update] def index @bages = Bage.all end def new @bage = Bage.new end def create @bage = Bage.new(bage_params) if @bage.save redirect_to admin_bages_path, notice: "Награда успешно создана" else render :new end end def edit; end def update if @bage.update(bage_params) redirect_to admin_bages_path, notice: "Награда успешно обновлена" else render :edit end end def destroy @bage.destroy redirect_to admin_bages_path, notice: "Награда успешно удалена" end private def find_bage @bage = Bage.find(params[:id]) end def bage_params params.require(:bage).permit(:name, :image_url, :rule) end end
class BidsController < ApplicationController before_action :set_bid, only: [:accept, :show, :edit, :update, :destroy] def index @bids = policy_scope(Bid).order(created_at: :desc) end def dashboard # @event = Event.find(params[:id]) # @reviewed_user = User.find(params[:user_id]) # @order = Order.find(params[:id]) # @event = Event.find(params[:event_id]) @user = current_user authorize @user #PROFESSIONAL #bids made by professional @professional_bids = @user.bids #accepted bids - profesional #list all professional events @accepted_bids = Bids.where(user_id: current_user.id).where(status: "accepted") #pending @pending_bids = Bids.where(user_id: @user.id).where(status: "pending") #declined bids - profesional @declined_bids = Bids.where(user_id: @user.id).where(status: "declined") #list of events the professional has bid on @professional_events = Bid.where(user_id: @user.id) # @professional_events = [] # @professional_bids.events.each do |event| # @professional_events << event # end #HOST #list all host events @host_events = Event.where(user_id: @user.id) #bids recieved for each event @host_bids = Bid.where(user_id: @user.id) #BOTH #reviews made by user @reviews = Review.where(reviewed_user_id: @user.id) # respond_to do |format| # format.html #looks for views/users/dashboard.html.erb # format.js #looks for views/users/dashboard.js.erb # end end def show @bid = set_bid authorize @bid end def new @event = Event.find(params[:event_id]) @bid = Bid.new authorize @bid end def create @event = Event.find(params[:event_id]) @bid = Bid.new(bid_params) @bid.event = @event @bid.user = current_user @bid.price_cents = 100 @bid.sku = @bid.event.name authorize @bid if @bid.save flash[:success] = "Bid saved!" order = Order.create!(bid_sku: @bid.sku, amount: @bid.price, state: 'pending', user: current_user) redirect_to new_order_payment_path(order) # redirect will be to payment when we get there else render "events/show" end end def accept authorize @bid @bid.update(bid_params) if bid_params["status"] == "accepted" flash[:notice] = "You have successfully accepted #{@bid.user.first_name}" elsif bid_params["status"] == "declined" flash[:alert] = "You have declined #{@bid.user.first_name}" end redirect_to dashboard_path(anchor: "hostevents") end private def set_bid @bid = Bid.find(params[:id]) end def bid_params params.require(:bid).permit(:price, :description, :status, :quote) end def edit authorize @bid end def update authorize @bid end def destroy authorize @bid end end
require 'singleton' require 'fiber' require 'dist_server/server/rpc_define' require 'rubylib/tcp_client' class LoopIdGenerator include Singleton def initialize @id = 0 end def next_id if @id >= 0x7fffffff @id = 0 end @id += 1 end end class RemoteServer < TCPClient extend RPCDefine def initialize(*args) super(*args) @fiber = {} @message_handler = self end def set_message_handler(handler) @message_handler = handler end def on_shutdown super on_disconnect end def on_disconnect super for id, fiber in @fiber fiber.resume end @fiber.clear end def on_handle_pack(sender, pack) message = Message.create_from_pack(pack) if message.is_return_package? callback_id = message.get_callback_id params = message.get_return_params self.handle_return(callback_id, params) else self.on_message(self, message) end end def on_message(sender, message) if @message_handler.respond_to?(message.method) Fiber.current.instance_variable_set('@sender', sender) ret = @message_handler.send(message.method, *message.params) if message.need_return? ret_msg = Message.create_return_pack(message, ret) sender.send_pack(ret_msg.to_fs_pack) end return true end false end def handle_return(callback_id, ret) fiber = @fiber[callback_id] if !fiber.nil? @fiber.delete callback_id fiber.resume ret end end def send_message_async(msg) id = LoopIdGenerator.instance.next_id msg.set_callback_id(id) if self.send_pack(msg.to_fs_pack) @fiber[id] = Fiber.current Fiber.yield end end def send_message_sync(msg) self.send_pack(msg.to_fs_pack) end end
PROJECT_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..', '..')).freeze APP_NAME = 'testapp'.freeze When /^I generate a new rails application$/ do steps %{ When I run `bundle exec rails new #{APP_NAME}` And I cd to "#{APP_NAME}" And I write to "Gemfile" with: """ source "http://rubygems.org" gem 'rails', '3.0.12' gem 'sqlite3' """ And I successfully run `bundle install --local` } end When /^I configure the application to use "([^\"]+)" from this project$/ do |name| append_to_gemfile "gem '#{name}', :path => '#{PROJECT_ROOT}'" steps %{And I run `bundle install --local`} end When /^I run the rspec generator$/ do steps %{ When I successfully run `rails generate rspec:install` } end When /^I configure the application to use rspec\-rails$/ do append_to_gemfile "gem 'rspec-rails'" steps %{And I run `bundle install --local`} end When /^I configure the application to use shoulda-context$/ do append_to_gemfile "gem 'shoulda-context'" steps %{And I run `bundle install --local`} end When /^I configure the application to use shoulda$/ do append_to_gemfile "gem 'shoulda-matchers', '~> 1.0', :require => false" append_to_gemfile "gem 'shoulda-context', '~> 1.0', :require => false" append_to_gemfile "gem 'shoulda', :path => '../../..'" steps %{And I run `bundle install --local`} end When /^I configure the application to use shoulda-matchers$/ do append_to_gemfile "gem 'shoulda-matchers', '~> 1.0'" steps %{And I run `bundle install --local`} end When /^I configure a wildcard route$/ do steps %{ When I write to "config/routes.rb" with: """ Rails.application.routes.draw do match ':controller(/:action(/:id(.:format)))' end """ } end module AppendHelpers def append_to(path, contents) in_current_dir do File.open(path, "a") do |file| file.puts file.puts contents end end end def append_to_gemfile(contents) append_to('Gemfile', contents) end end World(AppendHelpers)
class Quiz < ActiveRecord::Base validates :subject, presence: true validates :question, presence: true has_many :answers accepts_nested_attributes_for :answers end
#!/Users/spamram/.rvm/rubies/ruby-1.9.2-p180/bin/ruby # Goal: # Find the first term in the Fibonacci sequence to contain 1000 digits. def fib_iter(a, b, p, q, count) if count == 0 return b elsif count % 2 == 0 fib_iter(a, b, (p*p + q*q), (2*p*q + q*q), (count/2)) else fib_iter((b*q + a*q + a*p), (b*p + a*q), p, q, (count-1)) end end def fib(n) fib_iter(1, 0, 0, 1, n) end def find_fib_by_digits(digits) ((digits*4.5).floor).upto((digits*5).floor) do |n| return n if fib(n).to_s.length == digits end end puts find_fib_by_digits(1000)
FactoryBot.define do factory :list do # Using City as it's the most suitable for the length validations. name { FFaker::AddressAU.city } user gift_day { 20.days.from_now } gift_value { rand(1..9999) } trait :with_santas do after(:create) do |list| FactoryBot.create_list(:santa, 8, list_id: list.id) end end trait :paid do limited { false } after(:create) do |list| FactoryBot.create(:processed_transaction, list_id: list.id) end end trait :unpaid do limited { true } end end end
require 'game' require 'player' describe Game do player_1 = Player.new("Kyaw") player_2 = Player.new("Li") subject(:game) { described_class.new(player_1, player_2) } it "accepts two players" do expect(game).to have_attributes( player1: player_1, player2: player_2) end it "damages the player" do expect(player_2).to receive(:receive_damage) game.attack(player_2) end it "knows the current player", :focus do expect(game.current_turn).to eq player_1 end it "switch the player turn", :focus do game.switch_turns expect(game.current_turn).to eq player_2 end end
module Gistim class Create def initialize(description: nil, alias_name: nil) @alias_name = alias_name @description = description end attr_reader :alias_name, :url def implement File.write(initialize_file_path, description) @url = create_empty clone File.delete(initialize_file_path) self end def hash url.nil? ? nil : url.chomp.gsub(/\A.+\//, '') end def description @description ||= '# Hello Gist!' end def directory "#{Gistim::Command.home}/#{name}" end def name alias_name || hash end private def clone Clone.clone(url, clone_directory: directory) end def create_empty # Execute `$ gist [some_file]` command and get gist url result url = `gist #{initialize_file_path}`.chomp url end def initialize_file_path 'GIST.md' end end end
class MeetingRoom < ApplicationRecord belongs_to :user has_many :bookings has_many :users, through: :bookings has_many :reviews, through: :bookings validates :name, :n_people, :hourly_price, :description, presence: true validates :hourly_price, numericality: { greater_than: 0, less_than: 200 } validates :n_people, numericality: { only_integer: true, greater_than: 0, less_than: 100 } validates :name, :description, :address, length: { maximum: 100 } validates :photo, presence: true geocoded_by :address after_validation :geocode, if: :address_changed? mount_uploader :photo, PhotoUploader end
class Proyecto < ApplicationRecord has_many :departamentos, dependent: :destroy validates :nombre, presence: true, uniqueness: true validates :caracteristica, presence: true validates :areacomun, presence: true validates :ubicacion, presence: true validates :precio, presence: true validates :foto_file_name, presence: false end
# frozen_string_literal: true # rubocop:todo all require 'spec_helper' class SessionTransactionSpecError < StandardError; end describe Mongo::Session do require_wired_tiger min_server_fcv '4.0' require_topology :replica_set, :sharded let(:session) do authorized_client.start_session(session_options) end let(:session_options) do {} end let(:collection) do authorized_client['session-transaction-test'] end before do collection.delete_many end describe '#abort_transaction' do require_topology :replica_set context 'when a non-Mongo error is raised' do before do collection.insert_one({foo: 1}) end it 'propagates the exception and sets state to transaction aborted' do session.start_transaction collection.insert_one({foo: 1}, session: session) expect(session).to receive(:write_with_retry).and_raise(SessionTransactionSpecError) expect do session.abort_transaction end.to raise_error(SessionTransactionSpecError) expect(session.send(:within_states?, Mongo::Session::TRANSACTION_ABORTED_STATE)).to be true # Since we failed abort_transaction call, the transaction is still # outstanding. It will cause subsequent tests to stall until it times # out on the server side. End the session to force the server # to close the transaction. kill_all_server_sessions end end context 'when a Mongo error is raised' do before do collection.insert_one({foo: 1}) end it 'swallows the exception and sets state to transaction aborted' do session.start_transaction collection.insert_one({foo: 1}, session: session) expect(session).to receive(:write_with_retry).and_raise(Mongo::Error::SocketError) expect do session.abort_transaction end.not_to raise_error expect(session.send(:within_states?, Mongo::Session::TRANSACTION_ABORTED_STATE)).to be true # Since we failed abort_transaction call, the transaction is still # outstanding. It will cause subsequent tests to stall until it times # out on the server side. End the session to force the server # to close the transaction. kill_all_server_sessions end end end describe '#with_transaction' do context 'callback successful' do it 'commits' do session.with_transaction do collection.insert_one(a: 1) end result = collection.find(a: 1).first expect(result[:a]).to eq(1) end it 'propagates callback\'s return value' do rv = session.with_transaction do 42 end expect(rv).to eq(42) end end context 'callback raises' do it 'propagates the exception' do expect do session.with_transaction do raise SessionTransactionSpecError, 'test error' end end.to raise_error(SessionTransactionSpecError, 'test error') end end context 'callback aborts transaction' do it 'does not raise exceptions and propagates callback\'s return value' do rv = session.with_transaction do session.abort_transaction 42 end expect(rv).to eq(42) end end context 'timeout with callback raising TransientTransactionError' do max_example_run_time 7 it 'times out' do start = Mongo::Utils.monotonic_time expect(Mongo::Utils).to receive(:monotonic_time).ordered.and_return(start) expect(Mongo::Utils).to receive(:monotonic_time).ordered.and_return(start + 1) expect(Mongo::Utils).to receive(:monotonic_time).ordered.and_return(start + 2) expect(Mongo::Utils).to receive(:monotonic_time).ordered.and_return(start + 200) expect do session.with_transaction do exc = Mongo::Error::OperationFailure.new('timeout test') exc.add_label('TransientTransactionError') raise exc end end.to raise_error(Mongo::Error::OperationFailure, 'timeout test') end end %w(UnknownTransactionCommitResult TransientTransactionError).each do |label| context "timeout with commit raising with #{label}" do max_example_run_time 7 # JRuby seems to burn through the monotonic time expectations # very quickly and the retries of the transaction get the original # time which causes the transaction to be stuck there. fails_on_jruby before do # create collection if it does not exist collection.insert_one(a: 1) end retry_test it 'times out' do start = Mongo::Utils.monotonic_time 11.times do |i| expect(Mongo::Utils).to receive(:monotonic_time).ordered.and_return(start + i) end expect(Mongo::Utils).to receive(:monotonic_time).ordered.and_return(start + 200) exc = Mongo::Error::OperationFailure.new('timeout test') exc.add_label(label) expect(session).to receive(:commit_transaction).and_raise(exc).at_least(:once) expect do session.with_transaction do collection.insert_one(a: 2) end end.to raise_error(Mongo::Error::OperationFailure, 'timeout test') end end end context 'callback breaks out of with_tx loop' do it 'aborts transaction' do expect(session).to receive(:start_transaction).and_call_original expect(session).to receive(:abort_transaction).and_call_original expect(session).to receive(:log_warn).and_call_original session.with_transaction do break end end end context 'application timeout around with_tx' do it 'keeps session in a working state' do session collection.insert_one(a: 1) expect do Timeout.timeout(1, SessionTransactionSpecError) do session.with_transaction do sleep 2 end end end.to raise_error(SessionTransactionSpecError) session.with_transaction do collection.insert_one(timeout_around_with_tx: 2) end expect(collection.find(timeout_around_with_tx: 2).first).not_to be nil end end end end
class Ticket < ActiveRecord::Base has_many :messages before_create :set_code def to_s messages.first.to_s end def set_code self.code = SecureRandom.hex(10) end end
# encoding: UTF-8 ## # Auteur JORIS TOULMONDE # Version 0.1 : Date : Thu Feb 11 16:27:55 CET 2016 # load 'ControleurPartie.rb' load 'Controleur.rb' load 'Vue.rb' load 'VueCase.rb' load 'Grille.rb' load 'VueChoixGrille.rb' load 'VueChoixAventureNiveau.rb' load 'Aventure.rb' #Classe permettant de selectionner les niveau de l'Aventure class ChoixAventureNiveau < Controleur @laventure # Liaison des boutons de la fenetre du choix de niveau de l'Aventure # # * *Args* : # - +laventure+ -> Aventure du joueur # - +jeu+ -> Session de jeu actuel du joueur # def ChoixAventureNiveau.Creer(laventure,jeu) new(laventure,jeu) end #Initialisation du menu pour demander à l'utilisateur quelle taille de grille il souhaite. def initialize(laventure,jeu) @choix = VueChoixNiveauAventure.Creer() @laventure = laventure @choix.niveau1.signal_connect('clicked'){ jeu = ControleurPartie.Creer(@laventure.choixNiveau(0),@laventure,jeu,0) jeu.uneVue.grille.afficherGrilleSolu() @choix.fenetre.hide_all } @choix.niveau2.signal_connect('clicked'){ jeu = ControleurPartie.Creer(@laventure.choixNiveau(1),@laventure,jeu,0) jeu.uneVue.grille.afficherGrilleSolu() @choix.fenetre.hide_all } @choix.niveau3.signal_connect('clicked'){ jeu = ControleurPartie.Creer(@laventure.choixNiveau(2),@laventure,jeu,0) jeu.uneVue.grille.afficherGrilleSolu() @choix.fenetre.hide_all } @choix.niveau4.signal_connect('clicked'){ jeu = ControleurPartie.Creer(@laventure.choixNiveau(3),@laventure,jeu,0) jeu.uneVue.grille.afficherGrilleSolu() @choix.fenetre.hide_all } @choix.niveau5.signal_connect('clicked'){ jeu = ControleurPartie.Creer(@laventure.choixNiveau(4),@laventure,jeu,0) jeu.uneVue.grille.afficherGrilleSolu() @choix.fenetre.hide_all } @choix.retour.signal_connect('clicked'){ jeu.joueur.laventure.aventureEtat = false EcranAccueil.new(jeu, Gtk::Window::POS_CENTER) @choix.fenetre.hide_all } @choix.quitter.signal_connect('clicked'){ Gtk.main_quit @choix.fenetre.hide_all } end end
class QuickSort def self.perform(array) new(array).sort(0, array.length - 1) end def self.comparisons_for(array) instance = new(array) instance.sort(0, array.length - 1) instance.comparison_count.tap do |c| raise "#{c} vs #{instance.raw_comparison_count}" unless c == instance.raw_comparison_count end end attr_reader :array, :comparison_count, :raw_comparison_count def initialize(array) @array = array.dup @comparison_count = 0 @raw_comparison_count = 0 end def sort(l, r) return array if l >= r @comparison_count += (r - l) final_pivot_index = partition(l, r) sort(l, final_pivot_index - 1) sort(final_pivot_index + 1, r) array end private def choose_pivot(l, r) array[l] end def partition(l, r) pivot = choose_pivot(l, r) i = l + 1 i.upto(r) do |j| @raw_comparison_count += 1 next unless array[j] < pivot array[i], array[j] = array[j], array[i] i += 1 end array[l], array[i - 1] = array[i - 1], array[l] return i - 1 end end class QuickSortWithLastElementPivot < QuickSort def choose_pivot(l, r) array[r].tap do |pivot| array[l], array[r] = array[r], array[l] end end end class QuickSortWithMedianOfThreePivot < QuickSort def self.median_of_three_index(array, l, r) length = r - l + 1 indices = [l, r, (length / 2.0).ceil - 1 + l] indices.sort_by! { |i| array[i] } indices[1] end def choose_pivot(l, r) index = self.class.median_of_three_index(array, l, r) array[index].tap do |pivot| array[l], array[index] = array[index], array[l] end end end if defined?(::RSpec) shared_examples_for "quick sort" do it 'sorts a list of integers properly' do described_class.perform([1, 6, 3, 2, 8, 4, 5, 7]).should eq([1, 2, 3, 4, 5, 6, 7, 8]) end it 'counts the number of comparisons' do described_class.comparisons_for([]).should eq(0) described_class.comparisons_for([1]).should eq(0) described_class.comparisons_for([2, 1]).should eq(1) end 0.upto(100) do |size| array = 1.upto(size).map { |_| rand(20) } it "sorts #{array} correctly" do described_class.perform(array).should eq(array.sort) described_class.comparisons_for(array) # should not raise an error end end end describe QuickSort do it_behaves_like "quick sort" end describe QuickSortWithLastElementPivot do it_behaves_like "quick sort" end describe QuickSortWithMedianOfThreePivot do it_behaves_like "quick sort" describe ".median_of_three_index" do specify do QuickSortWithMedianOfThreePivot.median_of_three_index([0, 1, 2], 0, 2).should eq(1) end specify do QuickSortWithMedianOfThreePivot.median_of_three_index([1, 0, 2], 0, 2).should eq(0) end specify do QuickSortWithMedianOfThreePivot.median_of_three_index([2, 0, 1], 0, 2).should eq(2) end specify do QuickSortWithMedianOfThreePivot.median_of_three_index([3, 0, 1, 2], 0, 3).should eq(3) end specify do QuickSortWithMedianOfThreePivot.median_of_three_index([2, 3, 1, 0], 0, 3).should eq(0) end specify do QuickSortWithMedianOfThreePivot.median_of_three_index([2, 1, 3, 0], 0, 3).should eq(1) end specify do QuickSortWithMedianOfThreePivot.median_of_three_index([4, 7, 1, 3, 6, 2, 5], 3, 6).should eq(6) end specify do QuickSortWithMedianOfThreePivot.median_of_three_index([4, 7, 1, 3, 6, 2, 5], 1, 5).should eq(3) end end end end if __FILE__ == $0 array = File.read('QuickSort.txt').split("\n").map(&:to_i) puts "First element as Pivot: #{QuickSort.comparisons_for(array)}" puts "Last element as Pivot: #{QuickSortWithLastElementPivot.comparisons_for(array)}" puts "Median of Three elements as Pivot: #{QuickSortWithMedianOfThreePivot.comparisons_for(array)}" end
Given(/^I am on the portfolio page$/) do Project.destroy_all project = Project.create(name: "Farm Fresh", when: DateTime.now) project.images.create(image: "https://unsplash.it/300/200/?random") visit portfolio_path end Then(/^I should see a the main title$/) do expect(page).to have_content 'Portfolio' end Then(/^I should see a list of projects$/) do expect(page).to have_css '#projectsContainer' expect(page).to have_css '.project' expect(find('#projectsContainer')).to have_content 'Farm Fresh' end When(/^I click on the project$/) do click_link 'More Info' end Then(/^I should be taken to the project page$/) do expect(current_path).to include "projects/" end
class User < ActiveRecord::Base acts_as_authentic has_many :qualifications belongs_to :industry has_many :histories has_one :profile has_attached_file :headshot, :styles => { :medium => "300x300>", :thumb => "100x100>" } #validates_attachment_content_type :headshot, :content_type => ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'] #validates_attachment_size :headshot, :less_than => 1.megabyte, :message => "must be smaller than 1MB" def deliver_password_reset_instructions! reset_perishable_token! Notifications.deliver_password_reset_instructions(self) end def work_experience for history in @user.histories @time = (history.end.month - history.start.month) + (12 * (history.end.year - history.start.year)) @experience = @time / 12.0 @experience.round(1).to_f total_experience += @experience end @work_experience = total_experience end end
class EventsController < ApplicationController def index team = Team.friendly.find(params[:team_id]) authorize team, :show_events? @events = PaginatingDecorator.new(team.events.recent.page params[:page]) @last_midnight = params[:date] || '' @last_project_path = params[:project_path] || '' end end
require 'rails_helper' RSpec.describe Account, type: :model do context "user sets this account as default" do subject(:account) { create(:account, :default) } it { is_expected.to be_default } it "can't be destroyed" do expect { account.destroy! }.to raise_error end end context "user doesn't sets this account as default" do subject(:account) { create(:account) } it { is_expected.not_to be_default } it "can be destroyed" do expect { account.destroy! }.not_to raise_error end end end
define :ruby_symlinks, action: :create, force: false, path: '/usr/bin' do rv = params[:name].to_s #rv = rv.slice(0..2).delete('.') if node[:platform] == 'gentoo' %w( ruby irb erb ri testrb rdoc gem rake ).each do |name| path = ::File.join(params[:path], name) scope = self link path do to path + rv action params[:action] unless params[:force] not_if do if ::File.exist?(path) && !::File.symlink?(path) scope.log "Not modifying non-symbolic-link #{path}" true end end end end end end
class ApplicationController < ActionController::Base #include SimpleCaptcha::ControllerHelpers protect_from_forgery def require_http_basic_auth authenticate_or_request_with_http_basic do |login, password| if login == ENV['BASIC_USER'] && password == ENV['BASIC_PASSWORD'] true else false end end end def initialize_options_partials @order ||= Order.new out={} Category.all.each do |cat| out[cat.id] = render_to_string(:partial => "common/options#{cat.partial}") end gon.partials = out end def current_user @current_user ||= User.find_by_auth_token( cookies[:auth_token]) if cookies[:auth_token] end helper_method :current_user def current_cart if current_user @cart ||= current_user.cart else if session[:cart_token] @cart ||= Cart.find_by_session_token(session[:cart_token].to_s) if @cart.nil? @cart = Cart.new @cart.generate_token(:session_token) session[:cart_token] = @cart.session_token @cart.save @cart end else @cart = Cart.new @cart.generate_token(:session_token) session[:cart_token] = @cart.session_token @cart.save @cart end end if @cart @cart else @cart = Cart.new @cart.generate_token(:session_token) session[:cart_token] = @cart.session_token @cart.save @cart end end helper_method :current_cart end
require 'spec_helper' describe CsvRowModel::DynamicColumnShared do let(:klass) do Class.new(OpenStruct) { include CsvRowModel::DynamicColumnShared } end let(:instance) { klass.new } let(:options) { {} } before do allow(instance).to receive(:column_name).and_return(:skills) allow(instance).to receive(:options).and_return(options) end describe "#header_models" do subject { instance.header_models } let(:context) { { skills: "waka" } } before { expect(instance).to receive(:context).and_return(OpenStruct.new(context)) } it "calls the method of the column_name on the context as an array" do expect(subject).to eql ["waka"] end context "when the context doesn't have #header_models_context_key" do let(:context) { {} } it "returns an empty array" do expect(subject).to eql [] end end end describe "#header_models_context_key" do subject { instance.header_models_context_key } it "defaults to the column_name" do expect(subject).to eql :skills end context "with option given" do let(:options) { { header_models_context_key: :something } } it "returns the option value" do expect(subject).to eql :something end end end end
class AddMetadataToReleaseOrder < ActiveRecord::Migration[5.0] def change add_column :release_orders, :metadata, :string, default: '{}' end end
#!/usr/bin/ruby # encoding: utf-8 #Neftalí Rodríguez Rodríguez puts "Iniciando Script Papelera.rb" VALOR1=ARGV[0] || "" VALOR2=ARGV[1] || "" VALOR3=ARGV[2] || "" def vaciar_papelera puts "¿Seguro que quiere borrar todo el contenido de la papelera? Escriba s/n" puts "*************************************************" system ("rm /home/nefta/Escritorio/Papelera/* -r -I") end def mostrar_papelera puts "Mostrando contenido de la papelera" puts "*************************************************" system ("ls /home/nefta/Escritorio/Papelera") puts "*************************************************" system ("tree /home/nefta/Escritorio/Papelera") end if VALOR1=="--help" then puts "Mostrando la ayuda de Papelera.rb" puts "*************************************************" puts "Escriba --help para mostrar este dialogo de ayuda" puts "Escriba -file y nombre de fichero o directorio a borrar" puts "Escriba --help para ayuda" puts "Escriba -r para recuperacion de archivos o directorios" puts "Escriba --clean para eliminar la papelera de forma definitiva" puts "Escriba --help para ayuda" elsif VALOR1=="-r" and VALOR2!="" then puts "Recuperando el archivo "+VALOR2+ VALOR3 puts "*************************************************" comando=("mv /home/nefta/Escritorio/Papelera/" +VALOR2+ " "+VALOR3) puts comando system(comando) elsif VALOR1=="--info" then mostrar_papelera elsif VALOR1=="--clean" then vaciar_papelera elsif VALOR1=="-i" then puts "MENU" puts "*************" puts "Escriba -borrar para borrar todo el contenido de la Papelera" puts "*************************************************" puts "Escriba -ver para mostrar el contenido de la Papelera" puts "*************************************************" s=$stdin.gets.chomp if (s=="-borrar") then vaciar_papelera elsif (s=="-ver") then mostrar_papelera else puts "No estas ejecutando bien el Script" end elsif VALOR1=="-file" and VALOR2!="" then if File.exist?('/home/nefta/Escritorio/Papelera') then puts "Enviando archivo a la Papelera "+VALOR2 borrar=("mv " +VALOR2+ " /home/nefta/Escritorio/Papelera/") puts borrar system(borrar) elsif system('mkdir /home/nefta/Escritorio/Papelera') puts "Creando Papelera" puts "Enviando archivo a la Papelera "+VALOR2 borrar=("mv " +VALOR2+ " /home/nefta/Escritorio/Papelera/") puts borrar system(borrar) end else puts "Introduce uno de los siguientes comandos" puts "****************************************" puts "papelera [ --help | -r file [ destino ] | --info | -i | --clean | -file ]" end
require 'rails_helper' RSpec.describe ProductSerializer do let(:product) { create(:product) } let!(:variant) { create(:variant, product: product) } let(:expected_serializer_hash) do { name: product.name, description: product.description, image: product.image, variants: [expected_variant_serializer_hash]} end let(:expected_variant_serializer_hash) do { waist: variant.waist, length: variant.length, style: variant.style, count: variant.count } end subject(:serializer_hash) do ProductSerializer.new(product).serializable_hash end it 'includes the name, description, image, and variants' do expect(serializer_hash).to eq(expected_serializer_hash) end end
class ApplicantsController < ApplicationController before_action :set_applicant #, only: [:profile, :qualifications_and_licences] # skip_before_action :authenticate_user! # def update_personal_details # if @applicant # @applicant.update_personal_details # end # end def profile if @applicant render :json => @applicant.personal_details_json, success: true, status: 200 end end def update_profile case params[:type] when 'personal_details' @applicant.update_personal_details(get_data_from_params) when 'contact_details' @applicant.update_contact_detail(get_data_from_params) when 'criminal_convictions' @applicant.update_criminal_details(get_data_from_params) when 'emergency_contact' @applicant.update_emergency_contact(get_data_from_params) when 'other' @applicant.update_other_info(get_data_from_params) when 'extra' @applicant.update_extra_info(get_data_from_params) render json: {extra: @applicant.slice(*Applicant::EXTRA_INFORMATION_PARAMS), success: true}, success: true, status: 200 and return end # @applicant.save if @applicant.errors.count == 0 render :json => @applicant.personal_details_json, success: true, status: 200 else render :json => unsuccessful_response("Update unsuccessful!").merge({errors: @applicant.errors}), success: false, status: 400 end end def get_data_from_params params[:data] end def update_picture if @applicant.update_attributes(picture: params[:picture]) render :json => {profile_pic_url: @applicant.picture.url, success: true}, success: true, status: 200 else render :json => unsuccessful_response("Could not upload the image").merge({errors: @applicant.errors}), success: false, status: 400 end end def update_resume if params[:resume] resume = Paperclip.io_adapters.for(params[:resume]) resume.original_filename = 'data-resume.pdf' @applicant.resume = resume @applicant.save render :json => {resume: @applicant.resume.url, success: true}, success: true, status: 200 else render :json => unsuccessful_response("Could not upload resume").merge({errors: @applicant.errors}), success: false, status: 400 end end def qualifications_and_licences if @applicant render :json => @applicant.qualification_and_licences_json end end def experiences if @applicant render :json => @applicant.experiences_json end end def extra if @applicant render :json => @applicant.extra_json end end def create_extra end def update_extra end def references if @applicant render :json => @applicant.referals_json end end private def set_applicant @applicant = Applicant.get_applicant_by_auth_token_and_email(get_token_header, get_email_header) applicant_not_found unless @applicant end def applicant_not_found render :json => unsuccessful_response("Applicant Not Found"), success: false, status: 404 end end
class AddLocationToProfiles < ActiveRecord::Migration def change add_column(:profiles, :location, :string, :limit => 254) end end
Redmine::Plugin.register :redmine_enhanced_textarea do name 'Redmine Enhanced Textarea plugin' author 'Benoit Zugmeyer & Florent Solt' description 'Enhanced Textarea' version '0.0.1' url 'https://github.com/florentsolt/redmine_enhanced_textarea' end class EnhancedTextareaViewListener < Redmine::Hook::ViewListener def view_layouts_base_html_head(context) javascript_include_tag("enhanced-textarea.js", :plugin => "redmine_enhanced_textarea") end end
class ConfirmedEventsController < ApplicationController skip_before_action :authorized, only: [:index, :show] def index @confirmed_events = ConfirmedEvent.all end def show end def new @event = Event.find(set_event) @confirmed_event = ConfirmedEvents.new end private def set_event @event = event.find(params[:id]) end end
#!/usr/bin/env ruby # Load the program function_address and display the addresses # of the main() and foo() functions. Function foo() prints # the value of global (external) variable errno to stdout, # yet we cannot obtain its address. require 'rubug/gdb' EXE = 'function_address' gdb = Rubug::Gdb.new resp = gdb.file EXE puts "File #{EXE} loaded" puts "Address of main(): " + gdb.function_address(:main).to_s puts "Address of foo(): " + gdb.function_address(:foo).to_s puts "Address of errno: " + gdb.function_address(:errno).to_s # oops! gdb.quit
require 'spec_helper' describe DataMapper::Mongo::Adapter, '#close_connection' do let(:object) { described_class.new(:default,{}) } subject { object.close_connection } context 'when adapter is connected' do let(:connection) { mock(:close => true) } before do object.instance_variable_set(:@connection,connection) end it 'should close the connection' do connection.should_receive(:close) subject end it 'should remove the connection' do subject object.instance_variable_get(:@connection).should be_false end end context 'when adapter is not connected' do it 'should be a noop' do subject end end end
require 'test_helper' class SignUpTest < Capybara::Rails::TestCase feature 'Sign Up' do before do visit root_path within('nav') do click_on 'Sign Up' end end scenario 'has valid content' do within('form') do fill_in 'Email', with: 'user@example.com' fill_in 'First name', with: 'First' fill_in 'Last name', with: 'Last' fill_in 'Password', with: 'testing' fill_in 'Password confirmation', with: 'testing' click_button 'Sign Up' end assert_equal current_path, root_path end scenario 'had invalid content' do within('form') do fill_in 'Email', with: 'user@example.com' fill_in 'First name', with: 'First' fill_in 'Last name', with: 'Last' fill_in 'Password', with: 'password' fill_in 'Password confirmation', with: 'badpassword' click_button 'Sign Up' end page.must_have_content "Password confirmation doesn't match Password" end end end
require 'spec_helper' describe Vine::Fastly::Mongoid do describe 'surrogate keys' do it 'should respond to table_key' do expect(Example::MongoidThing.table_key).to eq('example_mongoid_things') end it 'should respond to fastly_service_identifier' do expect(Example::MongoidThing.fastly_service_identifier).to eq('456') end it 'should respond to purge_all' do expect(Example::MongoidThing.purge_all).to eq({"status"=>"ok"}) end context 'with a instansiated object' do before :each do @thing = Example::MongoidThing.new end it 'should respond to record_key' do expect(@thing.record_key).to eq("example_mongoid_things/#{@thing.id}") end it 'should purge a singe entry' do expect(@thing.purge).to eq({"status"=>"ok"}) end end end end
#!/usr/bin/env ruby # -*- coding: utf-8 -*- # Copyright (C) 2010,2011 Yasuhiro ABE <yasu@yasundial.org> @basedir = File.dirname($0) require 'rubygems' require 'bundler/setup' require 'yalt' include YALTools::CmdLine require 'optparse' def option_parser ret = { :dbname => "", :outfile => "-", :descending => false, :include_docs => true, :max_numrows => false, :attachments => false, :page => 0, :unit => 15, :couch_label=>"", :couch_conf=>"", :debug => false, } OptionParser.new do |opts| opts.banner = <<-EOF Usage: #{File::basename($0)} dbname [-p page] [-u unit] [-i] [-d] [-y] [-x] EOF opts.separator '' opts.on('-a', '--attachments', 'Add encodeded data of attachments [too slow]') { |i| ret[:attachments] = i } opts.on('-i', '--show_index', 'Display ["id","key","value"] tags only') { |i| ret[:include_docs] = ! i } opts.on('-u', '--unit num_of_unit', 'Set the num of processing unit (default: 15)') { |u| ret[:unit] = u.to_i } opts.on('-p', '--page page', 'Set the num of pages (default: 1)') { |p| ret[:page] = p.to_i } opts.on('-r', '--reverse', 'Enable reverse mode') { |r| ret[:descending] = r } opts.on('-m', '--max_numrows', 'Enable max_numrows mode') { |m| ret[:max_numrows] = m } opts.on('-o', '--outfile outfile', "Set output filename or '-'.") { |f| ret[:outfile] = f } require 'socket' opts.on('-y', '--yaml_conf filename', "Set yaml conf file") { |c| ret[:couch_conf] = c } opts.on('-x', '--yml_label label', "Set label name in the yaml conf file (default: default.user)") { |l| ret[:couch_label] = l } opts.on('-d', '--debug', 'Enable the debug mode') { |g| ret[:debug] = g } opts.on_tail('-h', '--help', 'Show this message') { |h| $stderr.puts opts exit(1) } begin opts.parse!(ARGV) ret[:dbname] = ARGV[0] if ARGV.length == 1 rescue $stderr.puts opts $stderr.puts $stderr.puts "[error] #{$!}" exit(1) end if ret[:dbname] == "" $stderr.puts opts exit(1) end if ret[:couch_label] == "" ret[:couch_label] = get_default_yaml_label() end if ret[:couch_conf] == "" ret[:couch_conf] = get_default_yaml_conf(@basedir) end end return ret end ########## ## main ## ########## @opts = option_parser msg = {"debug"=>@opts} and $stderr.puts msg.to_json if @opts[:debug] @couch = getCouch(@opts[:couch_conf], @opts[:couch_label], @opts[:debug]) opts = {} ## basic options opts["limit"] = @opts[:unit] opts["include_docs"] = @opts[:include_docs] opts["descending"] = @opts[:descending] msg = {"opts"=>opts} $stderr.puts msg.to_json if @opts[:debug] view = YALTools::YaAllDocs.new(@couch, @opts[:dbname]) view.debug = @opts[:debug] if @opts[:max_numrows] msg = { "max_numrows" => view.max_numrows(opts) } begin YALTools::CmdLine::save_data(msg.to_json, @opts[:outfile], "w") rescue exit end elsif @opts[:page] > 0 result_set, skip, page, max_page, max_rows = view.page(opts, @opts[:page], @opts[:unit]) msg = { "skip" => skip , "page" => page, "max_page" => max_page, "max_rows" => max_rows } $stderr.puts msg.to_json if @opts[:debug] begin result_set.each do |i| YALTools::CmdLine::save_data(i.to_json, @opts[:outfile], "w") end ensure exit end else begin case @opts[:attachments] when true view.each_with_attachments(opts, @opts[:page], @opts[:unit]) do |result_set, skip, page, max_page, max_rows| result_set.each do |i| YALTools::CmdLine::save_data(i.to_json, @opts[:outfile], "w") end end else view.each(opts, @opts[:page], @opts[:unit]) do |result_set, skip, page, max_page, max_rows| result_set.each do |i| YALTools::CmdLine::save_data(i.to_json, @opts[:outfile], "w") end end end ensure exit end end
require 'spec_helper' feature "Editing Issues" do let!(:user) { FactoryGirl.create(:user) } let!(:project) { FactoryGirl.create(:project) } let!(:issue) { FactoryGirl.create(:issue, project: project, user: user) } before do define_permission!(user, "view", project) define_permission!(user, "edit issues", project) sign_in_as! user visit '/' click_link project.name click_link issue.title click_link "Edit Issue" end scenario "Updating an issue" do fill_in "Title", with: "Make it really shiny!" click_button "Update Issue" expect(page).to have_content("Issue successfully updated.") within("#issue h3") do expect(page).to have_content("Make it really shiny!") end expect(page).to_not have_content(issue.title) end scenario "Updating an issue with invalid information" do fill_in "Title", with: "" click_button "Update Issue" expect(page).to have_content("Issue could not be updated.") end end
class User < ActiveRecord::Base devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable scope :without_user, lambda {|user| where("id <> :id", :id => user.id) } belongs_to :team STATUSES = {:in => 0, :out => 1}.freeze validates :status, :inclusion => {:in => STATUSES.keys} def current_sign_in_ip=(ip) super(User.string_ip_to_integer(ip)) save end def last_sign_in_ip=(ip) super(User.string_ip_to_integer(ip)) save end def self.string_ip_to_integer(ip) #If the ip is already in integer form then just send it along if ip.class == "String".classify.constantize ip_array = ip.split('.').map(&:to_i) integer_ip = 0 exponent = 3 ip_array.each do |octet| integer_ip += octet*256**exponent exponent -= 1 end integer_ip else ip end end def full_name [first_name, last_name].join(" ") end def status=(val) write_attribute(:status, STATUSES[val.intern]) end def status STATUSES.key(read_attribute(:status)) end end
require "bundler/setup" require "test/unit" require "geoip_city" class GeoIPTest < Test::Unit::TestCase def setup ## Change me! @dbfile = 'data/GeoLiteCity.dat' end def test_construction_default db = GeoIPCity::Database.new(@dbfile) assert_raises TypeError do db.look_up(nil) end h = db.look_up('24.24.24.24') assert_kind_of Hash, h assert_equal 'East Syracuse', h[:city] assert_equal 'United States', h[:country_name] end def test_construction_index db = GeoIPCity::Database.new(@dbfile, :index) h = db.look_up('24.24.24.24') assert_equal 'East Syracuse', h[:city] end def test_construction_filesystem db = GeoIPCity::Database.new(@dbfile, :filesystem) h = db.look_up('24.24.24.24') assert_equal 'East Syracuse', h[:city] end def test_construction_memory db = GeoIPCity::Database.new(@dbfile, :memory) h = db.look_up('24.24.24.24') assert_equal 'East Syracuse', h[:city] end def test_construction_filesystem_check db = GeoIPCity::Database.new(@dbfile, :filesystem, true) h = db.look_up('24.24.24.24') assert_equal 'East Syracuse', h[:city] end def test_bad_db_file assert_raises Errno::ENOENT do GeoIPCity::Database.new('/blah') end end end
SJYABackOffice::Application.routes.draw do resources :organizations resources :users do member do post 'invite', to: 'invites#create', as: :invite delete 'uninvite', to: 'invites#destroy', as: :uninvite get 'register/:invite_code', to: 'invites#edit', as: :rsvp match 'register', to: 'invites#update', via: [:patch, :put], as: :register match 'revoke', to: 'users#revoke', via: [:patch, :put], as: :revoke end end resources :documents do get 'download', on: :member, as: :download end resources :measures, except: [:show] do resources :measurements, except: [:index, :show] end get 'dashboard', to: 'measures#index', as: :dashboard resources :sessions, only: [:new, :create, :destroy] resources :password_resets, only: [:new, :create, :edit, :update] get 'cache/clear', to: 'cache#clear', as: :clear_caches get 'about', to: 'static_pages#about', as: :about get 'login', to: 'sessions#new', as: :login delete 'logout', to: 'sessions#destroy', as: :logout get 'reports', to: 'static_pages#reports', as: :reports get 'activity_summary', to: 'static_pages#activity_summary', as: :activity_summary get 'coalition_report', to: 'static_pages#coalition_report', as: :coalition_report get 'coalition_meeting_report', to: 'static_pages#coalition_meeting_report', as: :coalition_meeting_report get 'major_matrix_report', to: 'static_pages#major_matrix_report', as: :major_matrix_report get 'strategy_report', to: 'static_pages#strategy_report', as: :strategy_report mount Rapidfire::Engine => "/rf" root to: 'measures#index' end
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, :role has_one :profile, :dependent => :destroy after_save :create_profile has_many :events, :dependent => :destroy ROLES = %w[admin holder collector user] ROLES.each do |role_name| define_method(role_name.to_s + '?') do role == role_name.to_s end end end
require_relative './func_list' require_relative './tree' module GeneticProgramming class Solver def initialize(score_obj, max_gen = 500, mutate_rate = 0.1, crossover_rate = 0.1, exp_prob = 0.7, new_prob = 0.5) @score_obj = score_obj @max_gen = max_gen @mutate_rate = mutate_rate @crossover_rate = crossover_rate @exp_prob = exp_prob @new_prob = new_prob @tree_with_scores = [] end def evolve(pop_size) population = Array.new(pop_size) { Tree.make_random_tree(@score_obj.param_size) } @max_gen.times do @tree_with_scores = population .map { |tree| {tree: tree, score: @score_obj.score(tree)} } .sort_by { |tws| tws[:score] } p @tree_with_scores.first[:score] break if @tree_with_scores.first[:score] == 0 population[0] = @tree_with_scores[0][:tree] population[1] = @tree_with_scores[1][:tree] (2..pop_size).each do |i| if rand > @new_prob population[i] = select_tree .crossover(select_tree, @crossover_rate) .mutate(@score_obj.param_size, @mutate_rate) else population[i] = Tree.make_random_tree(@score_obj.param_size) end end end @tree_with_scores.first[:tree].display @tree_with_scores.first[:tree] end def select_index Math.log(Math.log(rand) / Math.log(@exp_prob)).to_i end def select_tree @tree_with_scores[select_index][:tree] end end end
class CreateAddresses < ActiveRecord::Migration def change create_table :addresses do |t| t.string :recipient, null: false, limit: 100 t.string :line_1, null: false, limit: 100 t.string :line_2, limit: 100 t.string :city, null: false, limit: 100 t.string :state, null: false, limit: 20 t.string :postal_code, null: false, limit: 10 t.string :country_code, null: false, limit: 2 t.timestamps null: false end end end
require_relative '../../scraper/buycott' require_relative '../spec_helper' require 'httparty' require 'nokogiri' RSpec.describe 'buycott', roda: :app do before(:each) do @scraper = Buycott.new end it '/valid item' do res = @scraper.scrape("756619009407") expect(res[:code]).to eq "756619009407" expect(res[:valid]).to eq true expect(res[:description]).to eq "Elenco WK-106 Hook Up Wire Kit. 6- 25' Rolls (red, Black, Green, Yellow, White" expect(res[:image_url]).to eq "http://images10.newegg.com/ProductImageCompressAll200/A3C6_1_201611041343676280.jpg" expect(res[:provider]).to eq "buycott.rb" end it '/invalid item' do res = @scraper.scrape("065633128507333336666") expect(res[:code]).to eq "065633128507333336666" expect(res[:valid]).to eq false expect(res[:description]).to eq "" expect(res[:image_url]).to eq "" expect(res[:provider]).to eq "buycott.rb" end end
class User < ApplicationRecord rolify # Con este método encriptamos al password y generamos el método "authenticate" # que será usado por Knock has_secure_password has_one :escort_profile, dependent: :destroy before_save :downcase_email, :downcase_username VALID_EMAIL_REGEX = /\A([\w+\-].?)+@[a-z]+[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i validates :username, presence: true, uniqueness: { case_sensitive: false } validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } validates :password, presence: true, length: { minimum: 6, maximum: 50 }, allow_nil: true private # Se encarga de que email tenga sólo letras minúsculas def downcase_email self.email.downcase! end def downcase_username self.username.downcase! end end
require('rspec') require('word_count') describe('String#word_count') do it ('return a single word') do expect('peck'.word_count("peck")).to(eq(1)) end it ('returns 0 if no word matches are found') do expect('peck'.word_count("dog")).to(eq(0)) end it ('return how frequently a word appears in a given string') do expect('peck'.word_count("if peter piper picked a peck of pickled peppers wheres the peck of pickled peppers peter piper picked")).to(eq(2)) end it ('return how frequently a word appears in a given string regardless of formatting and punctuation') do expect('peck'.word_count("If Peter Piper picked a peck of pickled peppers, where's the peck of pickled peppers Peter Piper picked?")).to(eq(2)) end end
# http://www.mudynamics.com # http://labs.mudynamics.com # http://www.pcapr.net require 'rubygems' require 'environment' require 'pcapr_local/config' require 'pcapr_local/scanner' require 'pcapr_local/server' require 'pcapr_local/xtractr' require 'logger' module PcaprLocal START_SCRIPT = File.join(ROOT, 'bin/pcapr_start.rb') # We share a single Logger across all of pcapr.Local. Logger = Logger.new(STDOUT) # Recreate logger using configured log location. LOGFILE = "server.log" def self.start_logging log_dir if log_dir and not log_dir.empty? if const_defined? :Logger remove_const :Logger end logfile = File.join(log_dir, LOGFILE) FileUtils.mkdir_p log_dir const_set :Logger, Logger.new(logfile, 5) end end # Start xtractr instance manager. def self.start_xtractr config xtractr_config = config['xtractr'].merge( "index_dir" => config.fetch("index_dir"), "pcap_dir" => config.fetch("pcap_dir") ) Xtractr.new xtractr_config end # Start file system scanner. def self.start_scanner config, db, xtractr scanner_config = config.fetch('scanner').merge( "index_dir" => config.fetch("index_dir"), "pcap_dir" => config.fetch("pcap_dir"), "db" => db, "xtractr" => xtractr ) PcaprLocal::Scanner.start scanner_config end # Start webserver UI/API def self.start_app config, db, scanner, xtractr app_config = config.fetch "app" root = File.expand_path(File.dirname(__FILE__)) app_file = File.join(root, "pcapr_local/server.rb") PcaprLocal::Server.run! \ :app_file => app_file, :dump_errors => true, :logging => true, :port => app_config.fetch("port"), :bind => app_config.fetch("host"), :db => db, :scanner => scanner, :xtractr => xtractr end def self.get_db config PcaprLocal::DB.get_db config.fetch("couch") end def self.start config=nil config ||= PcaprLocal::Config.config # Check that server is not already running. check_pid_file config['pidfile'] # Start logging. if config["log_dir"] start_logging config['log_dir'] end start_msg = "Starting server at #{config['app']['host']}:#{config['app']['port']}" Logger.info start_msg puts start_msg puts "Log is at #{config['log_dir']}/#{LOGFILE}" # Deamonize unless config['debug_mode'] puts "Moving server process to the background. Run 'stoppcapr' to stop the server." Process.daemon end # Create pid file that will be deleted when we shutdown. create_pid_file config['pidfile'] # Get database instance db = get_db config # Xtractr manager xtractr = start_xtractr config # Start scanner thread scanner = start_scanner config, db, xtractr # Start application server start_app config, db, scanner, xtractr end def self.check_pid_file file if File.exist? file # If we get Errno::ESRCH then process does not exist and # we can safely cleanup the pid file. pid = File.read(file).to_i begin Process.kill(0, pid) rescue Errno::ESRCH stale_pid = true rescue end unless stale_pid puts "Server is already running (pid=#{pid})" exit end end end def self.create_pid_file file File.open(file, "w") { |f| f.puts Process.pid } # Remove pid file during shutdown at_exit do Logger.info "Shutting down." rescue nil if File.exist? file File.unlink file end end end # Sends SIGTERM to process in pidfile. Server should trap this # and shutdown cleanly. def self.stop config=nil user_config = Config.user_config_path if File.exist?(user_config) config = PcaprLocal::Config.config user_config pid_file = config["pidfile"] if pid_file and File.exist? pid_file pid = Integer(File.read(pid_file)) Process.kill -15, -pid end end end end if __FILE__ == $0 PcaprLocal.start end
name 'mcc-stack' maintainer 'Rachel Kawula' maintainer_email 'rkawula@gmail.com' license 'All rights reserved' description 'Development environment for http://millscc.herokuapp.com' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.1.0' depends 'apt'
require 'json' require 'spec_helper' require_relative '../lib/swagger_definition_extractor.rb' describe SwaggerDefinitionExtractor do let :swagger1_definition_extractor do double 'swagger1_definition_extractor' end let :swagger2_definition_extractor do double 'swagger2_definition_extractor' end context 'when extracing information from Swagger 1.x document' do subject do SwaggerDefinitionExtractor.new(swagger1_definition_extractor, swagger2_definition_extractor) end let :content do '{ "host": "fuse-equipment-api.herokuapp.com", "swaggerVersion": "1.2" }' end let :json do JSON.parse(content) end it 'should use Swagger1DefinitionExtractor if API version is 1' do expect(swagger1_definition_extractor).to receive(:extract)\ .with(json) subject.extract(json) end end context 'when extracting information from Swagger 2.x document' do subject do SwaggerDefinitionExtractor.new(swagger1_definition_extractor, swagger2_definition_extractor) end let :content do '{ "host": "fuse-equipment-api.herokuapp.com", "swagger": "2.0" }' end let :json do JSON.parse(content) end it 'should use Swagger2DefinitionExtractor if API version is 2' do expect(swagger2_definition_extractor).to receive(:extract) .with(json) subject.extract(json) end end context 'when extracting information from an unsupported Swagger document' do subject do SwaggerDefinitionExtractor.new(swagger1_definition_extractor, swagger2_definition_extractor) end let :content do '{ "host": "fuse-equipment-api.herokuapp.com", "swagger": "3.0" }' end let :json do JSON.parse(content) end it 'should raise an error' do expect do subject.extract(json) end.to raise_error('Unsupported Swagger version') end end end
require "codeunion/command/base" require "codeunion/api" require "codeunion/helpers/text" require "codeunion/search" require "faraday" require "rainbow" require "io/console" module CodeUnion module Command # The built-in `codeunion search` command class Search < Base include CodeUnion::Helpers::Text def run results.inject([]) do |lines, result| lines.push(CodeUnion::Search::ResultPresenter.new(result).to_s) lines << format_output("") end.join("\n") end def results @results ||= api.search(options) end private def api @api ||= CodeUnion::API.new("api.codeunion.io", "v1") end end end end
module LemonadeStand class NormalEvent < Event def modify choice choice.max_sales end end end
#Mixing in this module will allow any GameObject to react to commands. module Reacts def initialize(*args) super init_reactor end #Checks if a given object uses the reactions stored in a given file. def uses_reaction? file @reactions_files.include? file end # Automatically set up the reactor when we extend an object def self.extended(obj) obj.init_reactor end def init_reactor @reactor ||= Reactor.new(self) @reaction_files ||= Set.new @tick_actions ||= TickActions.new alert(Event.new(:Generic, :action => :init)) end #Clears out current reactions and loads the ones #which have previously been loaded from a file. def reload_reactions @reactor.clear if @reaction_files @reaction_files.each do |file| load_reactions file end end alert(Event.new(:Generic, :action => :init)) end #Deletes all reactions but does not clear the list of reaction files. def unload_reactions @reactor.clear if @reactor @reaction_files.clear if @reaction_files end #Loads reactions from a file. # #Note: This appends them to the existing reactions. To reload, #use Mobile#reload_reactions def load_reactions file @reaction_files ||= Set.new @reaction_files << file @reactor.load(file) alert(Event.new(:Generic, :action => :init)) end #Respond to an event by checking it against registered reactions. def alert(event) log "Got an alert about #{event}", Logger::Ultimate log "I am #{self.goid}", Logger::Ultimate reactions = @reactor.react_to(event) unless reactions.nil? reactions.each do |reaction| log "I am reacting...#{reaction.inspect}", Logger::Ultimate action = CommandParser.parse(self, reaction) unless action.nil? log "I am doing an action...", Logger::Ultimate changed #notify_observers(action) raise "This used to notify observers, not sure how this worked so need to fix this, most likely this will be rewritten before it becomes an issue." else log "Action did not parse: #{reaction}", Logger::Medium end end else log "No Reaction to #{event}", Logger::Ultimate end end #Returns a String representation of the reactions this GameObject has. def show_reactions if @reactor @reactor.list_reactions else "Reactor is nil" end end #Runs any actions set up on ticks. def run super @tick_actions ||= TickActions.new if @tick_actions.length > 0 @tick_actions.dup.each_with_index do |e, i| if e[0] <= 0 e[1].call if e[2] @tick_actions[i][0] = e[2] else @tick_actions.delete i end else e[0] -= 1 end end end end private #Determines if the object of an event is this object. # #Mainly for use in reaction scripts. def object_is_me? event event[:target] == self end #Parses command and creates a new event. #Unless delay is true, the event is added to to event handler. def act command, delay = false event = CommandParser.parse(self, command) return false if event.nil? #failed to parse raise "removed events this class no longer works, will probably be rewritten" #add_event event unless delay event end #Does "emote ..." def emote string act "emote #{string}" end #Does "say ..." def say output act "say #{output}" end #Does "sayto target ..." def sayto target, output target = target.name if target.is_a? GameObject act "sayto #{target} #{output}" end #Moves in the given direction def go direction act "go #{direction}" end #Calls Manager::get_object def get_object goid $manager.get_object goid end #Calls Manager::find def find name, container = nil $manager.find name, container end #Randomly performs an act from the given list def random_act *acts act acts[rand(acts.length)] end #Do the given act with the given probability (between 0 and 1) def with_prob probability, action = "" if rand < probability if block_given? yield else act action end true else false end end #Moves randomly, but only within the same area def random_move probability = 1 return if rand > probability room = get_object self.container area = room.area unless room.nil? exits = room.exits.select do |e| other_side = get_object e.exit_room not other_side.nil? and other_side.area == area end.map {|e| e.alt_names[0] } if exits.respond_to? :shuffle exits = exits.shuffle else exits = exits.sort_by { rand } end go exits[rand(exits.length)] end end #Creates an object and puts it in the creator's inventory if it has one def make_object klass obj = $manager.make_object klass inventory << obj if self.respond_to? :inventory obj end #Deletes an object def delete_object object $manager.delete object end #Checks if the given phrase was said in the event. def said? event, phrase if event[:phrase] event[:phrase].downcase.include? phrase.downcase else false end end #After the given number of ticks, execute the given block. def after_ticks ticks, &block @tick_actions << [ticks.to_i, block, false] end #After every number of ticks, execute the given block. def every_ticks ticks, &block @tick_actions << [ticks.to_i, block, ticks.to_i] end #Turns an array of actions into a chained sequence of commands. #This method returns the first event in the sequence, but does not #add it to the event queue. # #Options should be passed in as a hash. # # :initial_delay - delay before first action (Default: 0 seconds) # :delay - delay between actions (Default: 0 seconds) # :loop - true to repeat sequence infinitely (Default: false) def action_sequence sequence, options = {} delay = options[:delay] || 0 continuous_loop = false || options[:loop] first_step = sequence.shift if first_step.is_a? String first_step = CommandParser.parse self, sequence.shift end last_step = first_step if delay > 0 sequence.each do |next_step| next_step = CommandParser.parse self, next_step if next_step.is_a? String last_step.attach_event CommandParser.future_event self, delay, next_step last_step = next_step end else sequence.each do |next_step| next_step = CommandParser.parse self, next_step if next_step.is_a? String last_step.attach_event next_step last_step = next_step end end if options[:initial_delay] first_step = CommandParser.future_event self, options[:initial_delay], first_step end if continuous_loop last_step.attach_event first_step end first_step end def teleport item, destination, options = {} event = Event.new :Mobiles, {:action => :teleport, :player => self, :object => item, :in => destination}.merge(options) raise "re removed events this class no longer works and will probably be rewritten" # add_event event end def follow object, message = nil unless object.is_a? GameObject object = $manager.find event[:object] end if object.nil? self.output "Cannot follow that." return end self.info.following = object.goid object.info.followers ||= Set.new object.info.followers << self.goid if message object.output message unless message.empty? else object.output "#{self.name.capitalize} begins to follow you." end end def unfollow object, message = nil if self.info.following.nil? self.output "Not following anyone" return elsif not object.is_a? GameObject object = $manager.find object end if object.nil? self.output "Cannot follow that." return end self.info.following = nil object.info.followers.delete self.goid $stderr.puts "GOT AWAY WITH IT" if message object.output message unless message.empty? else object.output "#{self.name.capitalize} is no longer following you." end end end class TickActions def initialize @tick_actions = [] end def length @tick_actions.length end def each_with_index &block @tick_actions.each_with_index &block end def delete item @tick_actions.delete item end def << obj @tick_actions << obj end def marshal_dump "" end def marshal_load *args @tick_actions = [] end end
require 'rails_helper' describe ProductsController, type: :controller do before do @user = FactoryBot.create(:user) end describe 'GET #index' do it 'loads index template' do get :index expect(response).to be_ok expect(response).to render_template('index') end end context 'GET #new' do before do sign_in @user end it 'redirects to login when not logged in' do get :new, expect(response).to be_ok end end context 'GET #edit' do it 'shows login page' do get :edit, params: {id: @product.id} expect(response).to redirect_to new_user_session_path end end context "POST #create" do before do sign_in @user end it "creates new product" do @product = FactoryBot.create(:product) expect(response).to be_successful end it "throws error creating a product" do expect(Product.new(price:'string', description: '')).not_to be_valid end end describe "PATCH #update" do context "with good data" do before do sign_in @user end it "updates product and redirects" do patch :update, id: @product.id, product: { name: "berlinracerbike", price: "5", description: 'fantastic'} expect(response).to be_redirect end end context 'DELETE' do before do sign_in @user end it 'can delete product' do delete :destroy, params: { id: @product.id } expect(response).to redirect_to products_url end end end end
class MailingListsPresenter class Result attr_reader :emails, :metadata_fields def initialize(emails, metadata_fields = []) @emails = emails @metadata_fields = metadata_fields.map(&:to_s) end end class WaitlistsResult < Result attr_reader :run def initialize(run, *args) super(*args) @run = run end end def self.policy_class MailingListsPolicy end attr_reader :convention def initialize(convention) @convention = convention end def event_proposers event_proposals = convention.event_proposals .where.not(status: [:draft, :rejected, :dropped]) .includes(owner: :user) .order_by_title Result.new( event_proposals.map do |event_proposal| ContactEmail.new( event_proposal.owner.email, event_proposal.owner.name_without_nickname, title: event_proposal.title ) end, [:title] ) end def team_members events = convention.events.active .includes(team_members: { user_con_profile: :user }) .order_by_title emails_by_event = events.each_with_object({}) do |event, hash| hash[event] = team_member_emails_for_event(event) end.to_h Result.new( events.flat_map { |event| emails_by_event[event] }, [:event] ) end def ticketed_attendees user_con_profiles = convention.user_con_profiles .joins(:ticket) .includes(:user) .sort_by { |ucp| ucp.name_inverted.downcase } Result.new(ContactEmail.from_user_con_profiles(user_con_profiles)) end def users_with_pending_bio pending_bio_users = convention.user_con_profiles .can_have_bio .includes(:user) .select { |user_con_profile| user_con_profile.bio.blank? } Result.new(ContactEmail.from_user_con_profiles(pending_bio_users.sort_by(&:name_inverted))) end def waitlists runs = convention.runs .where(id: convention.signups.waitlisted.select(:run_id)) .includes(signups: { user_con_profile: :user }) .order(:starts_at) runs.map do |run| emails = run.signups.select(&:waitlisted?).map do |signup| ContactEmail.from_user_con_profile(signup.user_con_profile) end WaitlistsResult.new(run, emails) end end def whos_free(timespan) busy_user_con_profile_ids = Set.new( signups_during_timespan(timespan).map(&:user_con_profile_id) ) ticketed_user_con_profiles = convention.user_con_profiles .includes(:user) .where(receive_whos_free_emails: true) .joins(:ticket) free_user_con_profiles = ticketed_user_con_profiles .reject { |user_con_profile| busy_user_con_profile_ids.include?(user_con_profile.id) } Result.new(ContactEmail.from_user_con_profiles(free_user_con_profiles)) end private def team_member_emails_for_event(event) if event.con_mail_destination == 'event_email' && event.email.present? [ContactEmail.new(event.email, "#{event.title} Team", event: event.title)] else event.team_members.select(&:receive_con_email).map do |team_member| ContactEmail.new( team_member.user_con_profile.email, team_member.user_con_profile.name_without_nickname, event: event.title ) end end end def signups_during_timespan(timespan) signups_scope = convention.signups.where.not(state: 'withdrawn').includes(run: :event) signups_scope.select do |signup| signup.run.timespan.overlaps?(timespan) end end end
# coding: utf-8 lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'ogp/version' Gem::Specification.new do |spec| spec.name = 'ogp' spec.version = OGP::VERSION spec.authors = ['Jean-Philippe Couture'] spec.email = ['jcouture@gmail.com'] spec.summary = 'Simple Ruby library for parsing Open Graph prototocol information.' spec.description = 'Simple Ruby library for parsing Open Graph prototocol information. See http://ogp.me for more information.' spec.homepage = 'https://github.com/jcouture/ogp' spec.license = 'MIT' spec.files = `git ls-files`.split("\n") spec.executables = `git ls-files -- bin/*`.split("\n").map { |f| File.basename(f) } spec.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") spec.require_paths = ['lib'] spec.required_ruby_version = '>= 2.7' spec.add_dependency 'oga', '~> 3.3' spec.add_development_dependency 'bundler', '~> 2.1' spec.add_development_dependency 'rake', '~> 13.0' spec.add_development_dependency 'rspec', '~> 3.10' spec.add_development_dependency 'rubocop', '~> 1.12' end
class RemoveSendTypeFromAnnouncement < ActiveRecord::Migration[5.1] def change remove_column :announcements, :sendType, :string end end
module MultiInfo class API # Used to parse HTTP responses returned from MultiInfo API calls. class Response class << self # Returns the HTTP response body data as a hash. def parse(response_arr) return { :status => 'OK' } if API.test_mode command, http_response = response_arr response_rows = http_response.split(/\r\n|\n/) response_status, response_body = response_rows[0], response_rows[1..-1] if response_status.to_i < 0 raise MultiInfo::API::Error.new(response_status, response_body.first) else response_hash(command, response_body).merge({:status => response_status}) end end private def response_hash(command, response) resp_hash = {} API_RESPONSES[command].each_with_index { |message_key, i| resp_hash[message_key] = response[i] } resp_hash end public API_RESPONSES = { # Hash keys for each response lines. # Line no 1 is skipped as it always is 'status' 'sendsms' => [ :sms_id # 2 ], 'cancelsms' => [ :cancel_status # 2 ], 'infosms' => [ :sms_id, # 2 :message_type, # 3 :message_body, # 4 :protocol_id, # 5 :coding_scheme, # 6 :service_id, # 7 :conector_id, # 8 :originator_sms_id, # 9 :priority, # 10 :send_date, # 11 :valid_to, # 12 :deliv_notif_request, # 13 :originator, # 14 :destination, # 15 :message_status, # 16 :status_date # 17 ], 'packageinfo' => [ :package_id, # 2 :sent_message_count, # 3 :waiting_message_count,# 4 :package_status # 5 ], 'getsms' => [ :sms_id, # 2 :sender, # 3 :destination, # 4 :message_type, # 5 :message_body, # 6 :protocol_id, # 7 :coding_scheme, # 8 :service_id, # 9 :conector_id, # 9 :receive_date # 10 ] } end end end end
# # Author:: Phillip Spies (<phillip.spies@dimensiondata.com>) # License:: Apache License, Version 2.0 # require 'chef/knife' require 'chef/knife/base_dimensiondata_command' # list networks in datacenter class Chef::Knife::DimensiondataNetworkCreate < Chef::Knife::BaseDimensiondataCommand banner "knife dimensiondata network create (options)" get_common_options option :network, :long => "--network NetworkName", :description => "Name to be used by network" option :description, :long => "--description Description", :description => "Description to be used by network" option :dc, :long => "--datacenter DC", :description => "Datacenter where server should be created" def run caas = get_dimensiondata_connection if (config[:network].nil? || config[:dc].nil?) show_usage fatal_exit("You must specify both network and datacenter") end result = caas.network.create(config[:network], config[:dc], config[:description]) puts "#{ui.color("NETWORK", :cyan)}: #{ui.color(result.result_detail.split(" ")[5].chomp(")"), :red)}" end end
class Band < ApplicationRecord validates :name, presence: true validates :name, uniqueness: true has_many :albums, foreign_key: :band_id, class_name: "Album" has_many :songs, through: :albums, source: :tracks belongs_to :band_leader, foreign_key: :user_id, class_name: "User" has_many :fanship, foreign_key: :band_id, class_name: "Following" has_many :followers, through: :fanship, source: :user end
# frozen_string_literal: true class WorkTimePolicy < ApplicationPolicy class Scope < Scope def resolve if user.admin? || user.manager? scope.all else scope.joins(:project).where('work_times.user_id=:user_id OR projects.leader_id=:user_id', user_id: user.id) end end end end
class User include Mongoid::Document include Mongoid::Timestamps field :email, type: String has_many :checkins, dependent: :destroy validates :email, presence: true, uniqueness: true def self.with_whitelist_domain_email(email) email.match(whitelist_domain_regex) ? where(email: email).first_or_create : nil end def self.whitelist_domain_regex /\A([\w+\-].?)+@#{ENV['email_domain']}\z/i end end
# Define a new class called Book that is a blueprint for future objects class Book attr_accessor :title, :author, :pages def initialize(title, author, pages) # Settings attributes of the objects to the parameters passed @title = title @author = author @pages = pages end end # Creation of a new object based on the class Book book1 = Book.new("Harry Potter", "JK Rowling", 400) book2 = Book.new("Lors of the rings", "Tolkien", 500) # Display book1 properties puts book1.title puts book2.author puts book2.pages
require "rails_helper" require_relative "../../../lib/data_scripts/nhf_study_export_script" describe NhfStudyExportScript do it "runs" do described_class.call end it "enables readonly mode when in dry run mode" do described_class.call(dry_run: true) expect(User.new).to be_readonly end it "changes nothing in dry run mode" do expect { described_class.call }.to_not change { Patient.count } end end
# Load RubyGems; You need these gems installed: # $ sudo gem install sinatra slop require 'rubygems' # # Parse command-line options # # Slop is a handy library to parse command-line options. require 'slop' $opts = Slop.parse!(:help => true) do on 'p', 'port', true, :default => 8080, :as => :integer on 'prefix', true, :default => "" end # # Sample Sinatra app # require 'sinatra' # Use the HTTP port specified with --port set :port, $opts[:port] # Top page get "#{$opts[:prefix]}/" do @dice = rand(6) + 1 erb :index end # Help page get "#{$opts[:prefix]}/whatsthis" do @proxy_url = "http://localhost:3017#{$opts[:prefix]}/whatsthis" @real_url = "http://localhost:#{$opts[:port]}#{$opts[:prefix]}/whatsthis" erb :help end # Views (embedded) __END__ @@layout <!DOCTYPE html> <html> <head> <style> body { margin-left: 20%; margin-right: 20%; } .box { border: 1px solid gray; padding: 1em; } .dice { font-size: x-large; } dt { font-weight: bold; } </style> </head> <body> <h1> <a href="<%= $opts[:prefix] %>/"> <font color="red">D</font><font color="blue">i</font><font color="orange">c</font><font color="green">e</font> </a> </h1> <%= yield %> </body> </html> @@index <p class="dice"> [ <% if @dice == 1 %> <font color="red">1</font> <% else %> <%= @dice %> <% end %> ] </p> <a href="<%= $opts[:prefix] %>/"> Roll again! </a> <br><br><br> <a href="<%= $opts[:prefix] %>/whatsthis"> What's this? </a> @@help <h2>What's this?</h2> <div class="box"> <p>This is a sample application for Spellbook.</p> </div> <h2>How to make Spellbook apps</h2> <div class="box"> <p> A Spellbook app is just a web application runs on localhost. You can make Spellbook apps with your favorite programming language! </p> <p> The only rule is that your app must take these options: --port and --prefix. </p> <dl> <dt>--port=XXX</dt><dd>HTTP port number.</dd> <dt>--prefix=YYY</dt><dd>Prefix included in url.</dd> </dl> <p> When Spellbook invokes an app, it passes these options like this: </p> <pre>$ /some/where/yourapp --port=<%= $opts[:port] %> --prefix="<%= $opts[:prefix] %>"</pre> <p> Then, Spellbook acts like a proxy server.<br> This url ( <a href="<%= @proxy_url %>"> <%= @proxy_url %> </a> ) <br> shows the content of <a href="<%= @real_url %>"> <%= @real_url %> </a>. </p> <p> This sample app is written in Ruby and Sinatra. See <%= File.expand_path __FILE__ %> for details. </p> </div>
require 'rails_helper' RSpec.describe Alert, type: :model do let(:user) { create(:user) } let(:portfolio) { create(:portfolio) } let(:stock) { create(:stock) } let(:alert) { Alert.create!(stock: stock, user: user, price_initial: stock.lasttradepriceonly, price_target: (stock.lasttradepriceonly + 0.5) , start: DateTime.now, expire: (DateTime.now + 3.months)) } it { is_expected.to belong_to(:user) } it { is_expected.to belong_to(:stock) } it { is_expected.to validate_presence_of(:user) } it { is_expected.to validate_presence_of(:stock) } describe "attributes" do it "responds to price_initial" do expect(alert).to respond_to(:price_initial) end it "responds to price_target" do expect(alert).to respond_to(:price_target) end end end
module AmenityHelper def amenity_icon(name) case name when "Sockets" "https://img.icons8.com/wired/64/000000/plug.png" when "WiFi" "https://img.icons8.com/wired/64/000000/wifi-logo.png" when "Coffee" "https://img.icons8.com/wired/64/000000/tea.png" when "Laptop-space" "https://img.icons8.com/dotty/80/000000/laptop.png" when "Covid-Secure" "https://img.icons8.com/dotty/80/000000/clean-hands.png" end end end
class AddLatitudeAndLongitudeToState < ActiveRecord::Migration[5.0] def change add_column :states, :latitude, :float add_column :states, :longitude, :float end end
class TaxSettingsController < ApplicationController before_action :set_tax_setting, only: [:edit, :update, :destroy] before_action :logged_in_user def index @tax_settings = TaxSetting.all @tax_setting = TaxSetting.new end def create TaxSetting.create(tax_setting_params) TaxSetting.order(:start_date).each do |setting| next_setting = TaxSetting.where("start_date > ?", setting.start_date).order(:start_date).first if next_setting.present? yesterday_of_start_date = next_setting.start_date - 1 setting.update(end_date: yesterday_of_start_date) end end redirect_to tax_settings_path end def edit @tax_settings = TaxSetting.all end def update @tax_setting.update(tax_setting_params) TaxSetting.order(:start_date).each do |setting| next_setting = TaxSetting.where("start_date > ?", setting.start_date).order(:start_date).first if next_setting.present? yesterday_of_start_date = next_setting.start_date - 1 setting.update(end_date: yesterday_of_start_date) end end redirect_to tax_settings_path end def destroy @tax_setting.destroy redirect_to tax_settings_path end private def tax_setting_params params.require(:tax_setting).permit(:start_date, :national_rate, :local_rate) end def set_tax_setting @tax_setting = TaxSetting.find(params[:id]) end end
require_relative "helpers" require_relative "../../lib/gaudi" require "minitest/autorun" require "mocha/minitest" class TestUtilities < Minitest::Test include TestHelpers def test_switch_platform_configuration File.stubs(:exist?).returns(true) mock_config = File.expand_path("system.cfg") File.stubs(:readlines).with(mock_config).returns(TestHelpers.system_config_test_data) mock_foo = File.expand_path("foo.cfg") mock_bar = File.expand_path("bar.cfg") File.expects(:readlines).with(mock_bar).returns(TestHelpers.platform_config_test_data + ["foo=bar"]) File.expects(:readlines).with(mock_foo).returns(TestHelpers.platform_config_test_data) system_config = Gaudi::Configuration::SystemConfiguration.new(mock_config) Gaudi::Configuration.switch_platform_configuration "./bar.cfg", system_config, "foo" do assert_equal("bar", system_config.platform_config("foo")["foo"]) end assert_nil(system_config.platform_config("foo")["foo"]) end end
class AddCurrencyRefToTracks < ActiveRecord::Migration[5.1] def change add_reference :tracks, :currency, foreign_key: true end end
class NormalizeCustomers < ActiveRecord::Migration def up add_column :sales, :customer_id, :integer Sale.reset_column_information Sale.find_each do |sale| new_customer = format_customer(sale.attributes["customer_and_account_no"]) customer = Customer.find_or_create_by(name: new_customer[0], account: new_customer[1]) sale.customer_id = customer.id sale.save end remove_column :sales, :customer_and_account_no end def down add_column :sales, :customer_and_account_no, :string Sale.find_each do |sale| sale.update(customer_and_account_no:"#{sale.customer.name} #{sale.customer.account}") sale.save end Customer.delete_all remove_column :sales, :customer_id end def format_customer(string) string.gsub(/[()]/, ('')).split(' ') end end
class DetPedido < ActiveRecord::Base belongs_to :pedido belongs_to :producto end
require 'mechanize' require "./lib/import/scraper_adapter.rb" class Scraper05 include ScraperAdapter def initialize stage @stage = stage @agent = Mechanize.new @page = @agent.get "#{archive}http://www.agile2005.org/track/#{stage}" end def archive "http://web.archive.org/web/20060106194738/" end def contents "/html/body/table/tr[2]/td[2]/table" end def fetch_items case @stage when "experience_reports", "educators_symposium" then @page./("#{contents}/tr/td[@class='title']").map(&:text) else @page./("#{contents}/tr/td/a/@name").map(&:text) end end def anchor case @stage when "experience_reports", "educators_symposium" then @page./("#{contents}/tr/td[@class='title']")[number].children.first else @page.at("#{contents}/tr/td/a[@name='#{marker}']") end end def type case @stage when "tutorials" then "Tutorial" when "experience_reports" then "Experience Report" when "workshops" then "Workshop" when "research_papers" then "Research Paper" when "educators_symposium" then "Educator Paper" when "intro_to_agile" then "Tutorial" else "Talk" end end def stage case @stage when "tutorials" then "Tutorials" when "experience_reports" then "Experience Reports" when "workshops" then "Workshops" when "research_papers" then "Research Papers" when "educators_symposium" then "Educator's Symposium" when "intro_to_agile" then "Introduction to Agile" else "Main" end end def code case @stage when "tutorials" then "TU" when "experience_reports" then "XR" when "workshops" then "WK" when "research_papers" then "RP" when "educators_symposium" then "ES" when "intro_to_agile" then "INTRO" else "XX" end end def title anchor./("..//text()").map(&:text).join(" ").gsub(/\n|\t|\r/,"").gsub(/ +/," ").strip end def description looking = anchor.parent.parent begin looking = looking.next_sibling end while looking and not looking.text.start_with?("Abstract") looking.text[9..-1].strip if looking end def speakers looking = anchor.parent.parent begin looking = looking.next_sibling end while looking and looking./("td[class='captionLeft']").empty? speakers = looking./("td[class='captionLeft']/text()").map do |each| each.text.split(/[:,]/).first.strip end if looking end def all_records @all_records || @all_records = File.readlines("data/Agile2005-files.txt") end def records id = "#{code}#{number+1}" result = all_records.select {|each| each.start_with? "#{id} "} result.map &:strip end end
require 'test_helper' require 'test_helper_functions' class AutoTranslateTest < Minitest::Test include TestHelperFunctions def setup define_test_values @lang3 = "it" @lang4 = "el" @text_db = Pompeu::TextDB.new @text_db.add_translation @target, @key, @lang, @text, @confidence, @translatable @text_db.add_translation @target, @key, @lang2, @text, @confidence, @translatable @text_db.add_translation @target, @key, @lang3, @text, @confidence, @translatable end def test_same_result intranslator = DummyTranslator.new translator = Pompeu::AutoTranslatorWithDoubleCheck.new intranslator text = @text_db.find_text @target, @key text, accuracy = translator.translate [@lang, @lang2, @lang3], text, @lang4 assert_equal @text, text assert_equal 3, accuracy end def test_different_result @text_db.add_translation @target, @key, @lang2, @text2, @confidence, @translatable @text_db.add_translation @target, @key, @lang3, @text2, @confidence, @translatable intranslator = DummyTranslator.new translator = Pompeu::AutoTranslatorWithDoubleCheck.new intranslator text = @text_db.find_text @target, @key text, accuracy = translator.translate [@lang, @lang2, @lang3], text, @lang4 assert_equal @text2, text assert_equal 2, accuracy end class DummyTranslator def translate origin_lang, text, end_lang text end end end
class Skill < ActiveRecord::Base has_and_belongs_to_many :courses has_many :completions belongs_to :category validates_presence_of :name, :handle, :category validates_uniqueness_of :handle scope :for_category, -> (category) { where(category: category) } def self.summarize(categories) table = self.arel_table cat_table = Category.arel_table categories.join(table).on(table[:category_id].eq cat_table[:id]) .project(table[:id].count.as("total_skills")) end end
def short_long_short(str1, str2) # if str1.size < str2.size # puts str1 + str2 + str1 # else # puts str2 + str1 + str2 # end arr = [str1, str2].sort_by { |str| str.size } puts arr[0] + arr[1] + arr[0] end short_long_short('hi', 'elephant') short_long_short('gorilla', 'big') short_long_short('', 'xyz')
class Admin::PostsController < Admin::ApplicationController load_and_authorize_resource respond_to :html, :xml, :json # GET /posts # GET /posts.xml def index canonical_url("/posts") @posts = Post.all respond_with(@posts) end # GET /posts/1 # GET /posts/1.xml def show canonical_url("/posts/#{params[:id]}") @post = Post.find(params[:id]) respond_with(@post) end # GET /posts/new # GET /posts/new.xml def new @post = Post.new respond_with(@post) end # GET /posts/1/edit def edit @post = Post.find(params[:id]) end # POST /posts # POST /posts.xml def create @post = Post.new(params[:post]) if @post.save flash[:notice] = 'Post was successfully created.' else flash[:error] = 'Post was not successfully created.' end respond_with(@post, :location => admin_post_path(@post)) end # PUT /posts/1 # PUT /posts/1.xml def update @post = Post.find(params[:id]) @post.update_attributes(params[:post]) respond_with(@post, :location => admin_post_path(@post)) end # DELETE /posts/1 # DELETE /posts/1.xml def destroy @post = Post.find(params[:id]) @post.destroy flash[:notice] = 'Successfully destroyed post.' respond_with(@post, :location => admin_posts_path) end end
require 'rails_helper' RSpec.describe "Api::V1::Messages", type: :request do fixtures :messages describe "GET /api/v1/messages" do it "メッセージ一覧を取得する" do get '/api/v1/messages' assert_response_schema_confirm(200) end it "従業員IDを指定してメッセージ一覧を取得する" do get '/api/v1/messages?employee_id=1' assert_response_schema_confirm(200) end end describe "POST /api/v1/messages" do it "メッセージの投稿に成功する" do post '/api/v1/messages', params: { store_id: 1, employee_id:1, message_text: "test" } # github actionsでrspecを動かすとここで400が返ってきてrspecが失敗する # 本当は201が返ってくる assert_response_schema_confirm end it "メッセージの投稿に失敗する" do post '/api/v1/messages', params: { employee_id:1, message_text: "test" } assert_response_schema_confirm(400) end end end
require 'vanagon/extensions/set/json' describe "Set" do describe "with JSON mixins" do let(:test_set) { Set['a', 'a', 'b', 'c'] } let(:json_set) { %(["a","b","c"]) } it "responds to #to_json" do expect(Set.new.respond_to?(:to_json)).to eq(true) end it "can be converted to a valid JSON object" do expect(JSON.parse(test_set.to_json)).to eq(JSON.parse(json_set)) end end end
class User < ApplicationRecord include UserOath devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :omniauthable, omniauth_providers: [:facebook] has_one :cart, dependent: :destroy has_many :authorizations validates :email, presence: true validates :password, presence: true end
# frozen_string_literal: true module Decidim module Abilities # Defines the abilities for a participatory process cpdp. Intended to be # used with `cancancan`. # This ability will not apply to organization admins. class ParticipatoryProcessCpdpAbility < ParticipatoryProcessRoleAbility # Overrides ParticipatoryProcessRoleAbility role method def role :cpdp end end end end
# -*- coding: utf-8 -*- module Mushikago module Hotaru class DomainDeleteRequest < Mushikago::Http::DeleteRequest def path; '/1/hotaru/domain/delete' end request_parameter :domain_name def initialize domain_name, options={} super(options) self.domain_name = domain_name end end end end
class Ticket < ApplicationRecord belongs_to :user has_many :ticket_messages end
module API module V1 module Entities class Property < Grape::Entity root 'properties', 'property' format_with(:iso_timestamp) { |dt| dt.iso8601 } expose :id expose :property_type expose :name expose :goal expose :description expose :price expose :user do |prop| prop.user.name end expose :property_info, using: API::V1::Entities::PropertyInfo with_options(format_with: :iso_timestamp) do expose :created_at expose :updated_at end expose :total_visits do |prop| prop.try(:total_visits) || prop.visits.count end end end end end
class HomeController < ApplicationController def index @posts = Post.all if is_bruised_thumb? @posts = Post.where("is_live is true").all unless is_bruised_thumb? @posts = @posts.order(created_at: :desc).limit(5) end def page render template: "home/#{params[:page]}" rescue ActionView::MissingTemplate redirect_to root_path, alert: 'Page not found!' end end
class CreateRatings < ActiveRecord::Migration def self.up create_table :ratings do |t| t.belongs_to :user t.belongs_to :reply t.integer :vote t.timestamps end add_index :ratings, :user_id add_index :ratings, :reply_id end def self.down drop_table :ratings end end
class AddColumnToWorkHours < ActiveRecord::Migration def change add_column :workhours, :approved, :boolean end end
$:.push File.expand_path("../lib", __FILE__) require 'wprails/version' Gem::Specification.new do |spec| spec.name = "wprails" spec.version = Wprails::VERSION spec.authors = ["cerebrumlab"] spec.email = ["delavegogroup@gmail.com"] spec.summary = "Russification version camaleon CMS" spec.description = "Russification version camaleon CMS" spec.homepage = "TODO: Put your gem's website or public repo URL here." spec.license = "MIT" # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or # delete this section to allow pushing this gem to any host. s.required_ruby_version = '>= 1.9.3' s.requirements << 'rails >= 4.1' s.requirements << 'ruby >= 1.9.3' s.requirements << 'imagemagick' # s.post_install_message = "Thank you for install Camaleon CMS." s.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md", "public/**/*"] s.test_files = Dir["test/**/*"] # deprecated in Rails 4 s.add_dependency 'bcrypt' s.add_dependency 'cancancan', '~> 1.10' s.add_dependency 'draper', '~> 1.3' s.add_dependency 'meta-tags', '~> 2.0' s.add_dependency 'mini_magick' s.add_dependency 'mobu' s.add_dependency 'will_paginate' s.add_dependency 'will_paginate-bootstrap' s.add_dependency 'breadcrumbs_on_rails' s.add_dependency 'font-awesome-rails' s.add_dependency 'protected_attributes' # remove in next versions # MEDIA MANAGER s.add_dependency 'fog', '~> 1.34' s.add_dependency 'aws-sdk', '~> 2' # development and test s.add_development_dependency "rspec" # s.add_development_dependency "capybara" # s.add_development_dependency "selenium-webdriver" end
# encoding: utf-8 require 'spec_helper' describe TTY::Table::Renderer::Basic, 'with multiline content' do let(:header) { nil } let(:object) { described_class } let(:table) { TTY::Table.new header, rows } subject(:renderer) { object.new table } context 'with escaping' do let(:rows) { [ ["First", '1'], ["Multiline\nContent", '2'], ["Third", '3']] } context 'without border' do it "renders single line" do expect(table.render(multiline: false)).to eq <<-EOS.normalize First 1 Multiline\\nContent 2 Third 3 EOS end end context 'with column widths' do it "renders single line" do expect(table.render(multiline: false, column_widths: [8,1])).to eq <<-EOS.normalize First 1 Multili… 2 Third 3 EOS end end context 'with border' do it "renders single line" do expect(table.render(:ascii, multiline: false)).to eq <<-EOS.normalize +------------------+-+ |First |1| |Multiline\\nContent|2| |Third |3| +------------------+-+ EOS end end context 'with header' do let(:header) { ["Multi\nHeader", "header2"] } it "renders header" do expect(table.render(:ascii, multiline: false)).to eq <<-EOS.normalize +------------------+-------+ |Multi\\nHeader |header2| +------------------+-------+ |First |1 | |Multiline\\nContent|2 | |Third |3 | +------------------+-------+ EOS end end end context 'without escaping' do let(:rows) { [ ["First", '1'], ["Multi\nLine\nContent", '2'], ["Third", '3']] } context 'without border' do it "renders every line" do expect(table.render(multiline: true)).to eq <<-EOS.normalize First 1 Multi 2 Line Content Third 3 EOS end end context 'with column widths' do it "renders multiline" do expect(table.render(multiline: true, column_widths: [8,1])).to eq <<-EOS.normalize First 1 Multi 2 Line Content Third 3 EOS end it 'wraps multi line' do expect(table.render(multiline: true, column_widths: [5,1])).to eq <<-EOS.normalize First 1 Multi 2 Line Conte nt Third 3 EOS end end context 'with border' do it "renders every line" do expect(table.render(:ascii, multiline: true)).to eq <<-EOS.normalize +-------+-+ |First |1| |Multi |2| |Line | | |Content| | |Third |3| +-------+-+ EOS end end context 'with header' do let(:header) { ["Multi\nHeader", "header2"] } it "renders header" do expect(table.render(:ascii, multiline: true)).to eq <<-EOS.normalize +-------+-------+ |Multi |header2| |Header | | +-------+-------+ |First |1 | |Multi |2 | |Line | | |Content| | |Third |3 | +-------+-------+ EOS end end end end
class StatusesController < ApplicationController before_filter :login_required, :except => [:user, :info] # GET /statuses # GET /statuses.xml def index @statuses = current_user.statuses.active respond_to do |format| format.html # index.html.erb format.xml { render :xml => @statuses } end end def info twitter = Twitter::Base.new(TWITTER_USER, TWITTER_PASSWORD) @info = twitter.rate_limit_status @users = User.all end def user user = User.find_by_login(params[:id]) if user @statuses = user.statuses render :action => 'index' else redirect_to '/' end end # GET /statuses/1 # GET /statuses/1.xml def show @status = current_user.statuses.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @status } end end # GET /statuses/new # GET /statuses/new.xml def new @status = current_user.statuses.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @status } end end # GET /statuses/1/edit def edit @status = current_user.statuses.find(params[:id]) end # POST /statuses # POST /statuses.xml def create @status = current_user.statuses.new(params[:status]) respond_to do |format| if @status.save flash[:notice] = 'Status was successfully created.' format.html { redirect_to(@status) } format.xml { render :xml => @status, :status => :created, :location => @status } else format.html { render :action => "new" } format.xml { render :xml => @status.errors, :status => :unprocessable_entity } end end end # PUT /statuses/1 # PUT /statuses/1.xml def update @status = current_user.statuses.find(params[:id]) respond_to do |format| if @status.update_attributes(params[:status]) flash[:notice] = 'Status was successfully updated.' format.html { redirect_to(@status) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @status.errors, :status => :unprocessable_entity } end end end # DELETE /statuses/1 # DELETE /statuses/1.xml def destroy @status = current_user.statuses.find(params[:id]) @status.destroy respond_to do |format| format.html { redirect_to(statuses_url) } format.xml { head :ok } end end end
class Employee < ApplicationRecord belongs_to :organization has_many :scores end
# == Schema Information # # Table name: trade_sandbox_template # # id :integer not null, primary key # appendix :string(255) # taxon_name :string(255) # term_code :string(255) # quantity :string(255) # unit_code :string(255) # trading_partner :string(255) # country_of_origin :string(255) # export_permit :string(255) # origin_permit :string(255) # purpose_code :string(255) # source_code :string(255) # year :string(255) # import_permit :string(255) # reported_taxon_concept_id :integer # taxon_concept_id :integer # require 'spec_helper' describe Trade::SandboxTemplate, :drops_tables => true do let(:annual_report_upload){ aru = build(:annual_report_upload) aru.save(:validate => false) aru } let(:sandbox_klass){ Trade::SandboxTemplate.ar_klass(annual_report_upload.sandbox.table_name) } let(:canis){ create_cites_eu_genus( :taxon_name => create(:taxon_name, :scientific_name => 'Canis') ) } let(:canis_lupus){ create_cites_eu_species( :taxon_name => create(:taxon_name, :scientific_name => 'lupus'), :parent => canis ) } let(:canis_aureus){ create_cites_eu_species( :taxon_name => create(:taxon_name, :scientific_name => 'aureus'), :parent => canis ) } describe :update do before(:each) do @shipment1 = sandbox_klass.create(:taxon_name => canis_lupus.full_name) end specify { @shipment1.update_attributes(:taxon_name => canis_aureus.full_name) @shipment1.reload.taxon_concept_id.should == canis_aureus.id } end describe :update_batch do before(:each) do @shipment1 = sandbox_klass.create(:taxon_name => canis_lupus.full_name) @shipment2 = sandbox_klass.create(:taxon_name => canis_aureus.full_name) end specify { sandbox_klass.update_batch( {:taxon_name => 'Canis aureus'}, [@shipment1.id] ) @shipment1.reload.taxon_concept_id.should == canis_aureus.id } end end
class SushiImagesController < ApplicationController # GET /sushi_images # GET /sushi_images.xml def index @sushi_images = SushiImage.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @sushi_images } end end # GET /sushi_images/1 # GET /sushi_images/1.xml def show @sushi_image = SushiImage.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @sushi_image } end end # GET /sushi_images/new # GET /sushi_images/new.xml def new @sushi_image = SushiImage.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @sushi_image } end end # GET /sushi_images/1/edit def edit @sushi_image = SushiImage.find(params[:id]) end # POST /sushi_images # POST /sushi_images.xml def create @sushi_image = SushiImage.new(params[:sushi_image]) respond_to do |format| if @sushi_image.save flash[:notice] = 'SushiImage was successfully created.' format.html { redirect_to(@sushi_image) } format.xml { render :xml => @sushi_image, :status => :created, :location => @sushi_image } else format.html { render :action => "new" } format.xml { render :xml => @sushi_image.errors, :status => :unprocessable_entity } end end end # PUT /sushi_images/1 # PUT /sushi_images/1.xml def update @sushi_image = SushiImage.find(params[:id]) respond_to do |format| if @sushi_image.update_attributes(params[:sushi_image]) flash[:notice] = 'SushiImage was successfully updated.' format.html { redirect_to(@sushi_image) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @sushi_image.errors, :status => :unprocessable_entity } end end end # DELETE /sushi_images/1 # DELETE /sushi_images/1.xml def destroy @sushi_image = SushiImage.find(params[:id]) @sushi_image.destroy respond_to do |format| format.html { redirect_to(sushi_images_url) } format.xml { head :ok } end end end
class Publication < ApplicationRecord belongs_to :applicant validates :title, :content, presence: true after_create_commit { broadcast_append_to "publications" } after_update_commit { broadcast_replace_to "publications" } after_destroy_commit { broadcast_remove_to "publications" } end
# -*- mode: ruby -*- # vi: set ft=ruby : VAGRANTFILE_API = 2 VAGRANT_ROOT = File.dirname(__FILE__) EXTRA_SETTINGS = File.join(VAGRANT_ROOT, 'extra_settings.yml') # Common config values BASE_VM_NAME = "ogs" BASE_VM_IP = "192.168.99" # Config values for the head node IP = ENV["OGS_IP"] || "%s.%s" % [BASE_VM_IP, 100] MEM = ENV["OGS_MEM"] || "1024" CPU = ENV["OGS_CPU"] || "2" # Config values for the worker nodes NWORKERS = ENV["OGS_NWORKERS"] || "2" WORKER_MEM = ENV["OGS_WORKER_MEM"] || "512" WORKER_CPU = ENV["OGS_WORKER_CPU"] || "1" # Helper function for creating the head node name def get_head_name() BASE_VM_NAME + "-head" end def get_worker_name(n) BASE_VM_NAME + "-worker" + n.to_s.rjust(2, "0") end Vagrant.configure(VAGRANTFILE_API) do |config| # We use Debian 8 64bit as the base image. config.vm.box = "debian/jessie64" # Default head node hostname. config.vm.hostname = get_head_name() # Disable shared folder. config.vm.synced_folder ".", "/vagrant", :disabled => true # Disable automatic keypair insertion. config.ssh.insert_key = false # Set up head node head_name = get_head_name() config.vm.define head_name do |head| head.vm.provision :hosts, :sync_hosts => true, :add_localhost_hostnames => false head.vm.hostname = head_name head.vm.network "private_network", ip: IP head.vm.provider "virtualbox" do |vb| vb.gui = false vb.name = head_name vb.customize ["modifyvm", :id, "--memory", MEM.to_i] vb.customize ["modifyvm", :id, "--cpus", CPU.to_i] end head.vm.define head_name do |t| end end # And do the same thing for all worker nodes N = [1, NWORKERS.to_i].max (1..N).each do |n| worker_name = get_worker_name(n) config.vm.define worker_name do |worker| worker.vm.provision :hosts, :sync_hosts => true, :add_localhost_hostnames => false worker.vm.hostname = worker_name worker.vm.network "private_network", ip: BASE_VM_IP + "." + (100 + n).to_s worker.vm.provider "virtualbox" do |vb| vb.gui = false vb.name = worker_name vb.customize ["modifyvm", :id, "--memory", WORKER_MEM.to_i] vb.customize ["modifyvm", :id, "--cpus", WORKER_CPU.to_i] end worker.vm.define worker_name do |t| end # Set up provisioning once when all nodes have been setup # https://www.vagrantup.com/docs/provisioning/ansible.html if n == N worker.vm.provision "ansible" do |ansible| ansible.limit = "all" ansible.playbook = "provision.yml" ansible.host_key_checking = false ansible.groups = { "head" => [head_name], "workers" => (1..N).map { |w| get_worker_name(w) } } # Extra variables can be added by editing the extra_settings.yml file ansible.extra_vars = YAML.load_file(EXTRA_SETTINGS) end end end end end
require('minitest/autorun') require('minitest/rg') require_relative('../shop') require_relative('../customer') class TestShop < MiniTest::Test def setup @hdmi = Stock.new("HDMI Cable", 5.99, 5000983746352, 56) @mouse = Stock.new("Mighty Mouse", 7.50, 5000392856632, 10) @monitor = Stock.new("40' Monitor", 199.99, 50000093665743, 5) @keyboard = Stock.new("Ergonomic Keyboard", 36.99, 5000009222546, 0) @jimbo = Customer.new("Jim", "Bobbertson", "Jimbo67", [@hdmi, @mouse], "5 Janefield Street, Glasgow, G17 5RT", "thisismypsassord123", 0) @bob = Customer.new("Bob", "Hegarty", "Bigbobo", [@monitor, @keyboard], "122a Muckleflats, Stirling, S45 3ER", "p@33w0rd99", 254.50) @simon = Customer.new("Simon", "Simpson", "Sososimpo", [], "45 Nice Street, Nice, N46 5GQ", "supersimpo3212", 235.43) @lees_shop = Shop.new([@jimbo, @bob, @simon], [@hdmi, @monitor, @mouse], { Monday: "8-5", Tuesday: "8-5", Wednesday: "8-5", Thursday: "8-5", Friday: "8-5", Saturday: "7-4" } ) end def test_shop_has_customers assert_equal(3, @lees_shop.customers.length) end def test_shop_has_stock assert_equal(3, @lees_shop.stock.length) end def test_display_opening_hours assert_equal("7-4", @lees_shop.check_opening_hrs(:Saturday)) end end
class Item < ApplicationRecord belongs_to :genre has_many :cart_items, dependent: :destroy has_many :order_items validates :name, presence: true validates :caption, presence: true # 整数値のみ、最小値0 validates :price, presence: true, numericality: {only_integer: true, greater_than_or_equal_to: 0 } attachment :image # 税込価格の表記 def add_tax_price (self.price * 1.10).round end def self.item_search(keyword) Item.where('name LIKE ?', "%#{keyword}%") end end
class ListSerializer < ActiveModel::Serializer attributes :id, :name, :user_id has_many :media, through: :media_lists end
Rails.application.routes.draw do root to: 'application#home', as: 'home' get '/login', to: 'sessions#new', as: 'login' post '/login', to: 'sessions#create', as: 'sign_in' delete '/logout', to: 'sessions#destroy', as: 'logout' resources :users do collection do get 'forgot' post 'validate_forgot' end member do get 'reset' post 'validate_reset' end end resources :lineups do resources :players, only: [:index, :create, :destroy] member do get 'compare' post 'add_comparison' get 'roster' post 'set_roster' end collection do get 'matchup' post 'add_matchup' end end resources :players, only: [:show] do collection do get 'search' get 'all', to: 'players#flex_index', as: 'all' post 'flex_create', as: 'flex_create' end end end
class CommentNotifier < ActionMailer::Base layout 'email' default from: "from@example.com" def new_comment(comment) @comment = comment mail to: comment.recipient.email, subject: "#{comment.user.name} commented on #{comment.review_request.title}" end end
require 'rails_helper' describe CourseStudent, type: :model do describe 'validations' do it { should validate_presence_of :grade } end describe 'relationships' do it { should belong_to :course } it { should belong_to :student } end describe 'attributes' do it 'has a grade' do student = Student.create(name: "Laura") course = Course.create(name: "Biology") course_student = course.course_students.create(grade: 89.5) student.course_students << course_student expect(course_student.grade).to eq(89.5) end end end