text
stringlengths
10
2.61M
class Dev def hello 'Hello dev' end end class User def initialize @name = 'Den' end def hello "Hello, #{@name}" end end
class CreateFooterSites < ActiveRecord::Migration def self.up create_table :footer_sites do |t| t.string :name t.string :legend t.string :destination t.string :link_target t.string :image_file_name t.string :image_content_type t.integer :image_file_size t.datetime :image_updated_at t.boolean :active t.boolean :published t.timestamps end end def self.down drop_table :footer_sites end end
class Pv < Formula homepage "http://www.ivarch.com/programs/pv.shtml" url "http://www.ivarch.com/programs/sources/pv-1.5.7.tar.bz2" sha1 "173d87d11d02a524037228f6495c46cad3214b7d" bottle do revision 1 sha1 "0c77b97448d2705d9e9f5a63ceafa42e483a21d9" => :yosemite sha1 "a49bcc1abe924b622d06fb15eb01141d0c252f40" => :mavericks sha1 "1441d97ae226d2cb3e3519ae714cf47940d6595a" => :mountain_lion end depends_on "gettext" fails_with :llvm do build 2334 end def install system "./configure", "--disable-debug", "--prefix=#{prefix}", "--mandir=#{man}" system "make", "install" end test do progress = pipe_output("#{bin}/pv -ns 4 2>&1 >/dev/null", "beer") assert_equal "100", progress.strip end end
# -*- encoding : utf-8 -*- require 'httparty' require 'json' module Prosper module Api class Conta include HTTParty base_uri ::Prosper::Api.config.url attr_accessor :attributes attr_accessor :errors def initialize(attributes = {}) self.attributes = attributes end def save self.attributes = self.class.post("/api/contas", :body => {:lancamento_financeiro => self.attributes}).parsed_response.symbolize_keys end def self.find(id) return nil if id.blank? prosper_object = get("/api/contas/#{id}").parsed_response.symbolize_keys prosper_object = {:id => id} if prosper_object.empty? Conta.new( prosper_object ) end def self.all Conta.where end def self.where(options = {}) list = get("/api/contas", :body => options).parsed_response resposta = [] list.each do |object| resposta << Conta.new(object.symbolize_keys) end resposta end def load! self.attributes = Conta.find(self.attributes[:id]).attributes end def method_missing(m, *args, &block) self.attributes[m.to_sym] end end end end
module Api module V2 class Api::V2::PlayersController < ApplicationController def index players = Player.all authorize! :read, players render json: players end end end end
class Pangram ALPHABET = %w(a b c d e f g h i j k l m n o p q r s t u v w x y z) def self.pangram?(sentence) (ALPHABET - sentence.downcase.split('')).empty? end end
# class Person # # attr_reader :name, :age # with this we dont need getter methods # # attr_writer :name, :age # with this we dont need setter methods # attr_accessor :name, :age # with this we dont need the reader or writer. depends on what you want to use. # def initialize(name, age) # @name = name # @age = age # end # def displayPerson # puts "Name: #{@name} Age: #{@age}" # end # # # GETTER # # def name # # @name # # end # # # SETTER # # def name(new_name) # # @name = new_name # # end # end # # p = Person.new("John", 25) # p.name = "Jack" # p.age = 30 # # p.displayPerson # # cannot reach instance variables to print out but can create a method to reach them # # # # puts p.name # puts p.name # puts p.age
require 'open-uri' module Calculators class JsonBasedCalculator MIN_ARRAY_LENGTH = 10 def price(data) json = JSON.load(data) arrays_count = count_arrays_number json, 10 arrays_count end def count_arrays_number(element, limit) result = 0 element.each_value do |value| if value.is_a?(Array) result += 1 if value.count > limit value.each do |array_value| result += count_arrays_number(array_value, limit) if array_value.respond_to? :each_value end elsif value.is_a?(Hash) result += count_arrays_number value, limit end end result end end end
class BooksController < ApplicationController before_action :set_book, only: [:show, :edit, :update, :destroy] # GET /books def index @books = Book.all end # GET /books/1 def show end # GET /books/new def new @book = Book.new end # GET /books/1/edit def edit end # book /books def create @book = Book.new(book_params) humanity_datailed = NewGoogleRecaptcha.get_humanity_detailed( params[:new_google_recaptcha_token], 'manage_books', NewGoogleRecaptcha.minimum_score, @book ) @book.humanity_score = humanity_datailed[:score] if humanity_datailed[:is_human] && @book.save redirect_to @book, notice: 'Book was successfully created.' else render :new end end # PATCH/PUT /books/1 def update humanity_datailed = NewGoogleRecaptcha.get_humanity_detailed( params[:new_google_recaptcha_token], 'manage_books' ) flash[:error] = "Looks like you are not a human" unless humanity_datailed[:is_human] if humanity_datailed[:is_human] && @book.update(params_with_humanity(humanity_datailed[:score])) redirect_to @book, notice: 'Book was successfully updated.' else render :edit end end # DELETE /books/1 def destroy @book.destroy redirect_to books_url, notice: 'Book was successfully destroyed.' end private def set_book @book = Book.find(params[:id]) end def book_params params.require(:book).permit(:author, :title) end def params_with_humanity(score) book_params.merge(humanity_score: score) end end
require 'gladiator' class Arena def initialize(name) @name = name.capitalize @gladiators = [] end def name @name end def gladiators @gladiators end def clear @gladiators = [] end def remove_gladiator(gladiator_name) @gladiators.delete_if { |gladiator| gladiator.name == gladiator_name } end def entertained? @gladiators.find { |gladiator| gladiator.name == "Maximus" } end def add_gladiator(gladiator) @gladiators << gladiator if @gladiators.length < 2 end def fight return "You need 2 gladiators in order for a fight to occur" if @gladiators.size < 2 if @gladiators.find { |gladiator| gladiator.name == "Maximus" } return @gladiators.select { |gladiator| gladiator.name == "Maximus" } end key_beats_value = { "Trident" => "Spear", "Spear" => "Club", "Club" => "Trident" } glad1 = @gladiators[0] glad2 = @gladiators[1] if key_beats_value[glad1.weapon] == glad2.weapon @gladiators.delete_at(1) @gladiators elsif key_beats_value[glad2.weapon] == glad1.weapon @gladiators.delete_at(0) @gladiators elsif glad1.weapon == glad2.weapon @gladiators = [] end end # def fight end
class Activity < ActiveRecord::Base validates :kind, :points, :action, presence: true def to_sentence "#{action} #{kind}" end end
class CreateProfiles < ActiveRecord::Migration def change create_table :profiles do |t| t.string :image_1, null: false, default: "default.jpg" t.string :image_2 t.string :image_3 t.string :image_4 t.string :image_5 t.text :fav_characters t.text :fav_spots t.text :fav_places t.string :guilty_pleasure t.string :occupation t.string :icon t.text :interests t.string :link t.string :quip t.integer :flags, null: false, default: 0 t.text :fb_interests t.integer :user_id, null: false t.timestamps end end end
require 'net/http' require 'net/https' require 'uri' require 'nokogiri' module GoogleAnalytics AUTH_URL = 'https://www.google.com/accounts/ClientLogin' BASE_URL = 'https://www.google.com/analytics' class NotAuthorized < StandardError; end class ResponseError < StandardError; end class Client def initialize(username, password) @username, @password = username, password end def login! data = { :accountType => 'GOOGLE_OR_HOSTED', :service => 'analytics', :Email => @username, :Passwd => @password } resp = request(URI.parse(AUTH_URL), :post, data) begin if resp =~ /^Auth\=(.+)$/ @auth = $1 else raise NotAuthorized, 'you cannot access this google account' end rescue ResponseError raise NotAuthorized, 'you cannot access this google account' end end def get(path, args=nil) api_request(path, :get, args) end def post(path, args=nil) api_request(path, :post, args) end def api_request(path, method, args) login! unless @auth url = URI.parse([BASE_URL, path].join) resp = request(url, method, args) Nokogiri::XML(resp) end def request(url, method=:get, data=nil) case method when :get url.query = encode(data) if data req = Net::HTTP::Get.new(url.request_uri) when :post req = Net::HTTP::Post.new(url.request_uri) req.body = encode(data) if data req.content_type = 'application/x-www-form-urlencoded' end req['Authorization'] = "GoogleLogin auth=#{@auth}" if @auth puts url.to_s http = Net::HTTP.new(url.host, url.port) http.use_ssl = (url.port == 443) res = http.start() { |conn| conn.request(req) } raise ResponseError, "#{res.code} #{res.message}" unless res.code == '200' res.body end protected def encode(data) data.map do |k,v| value = v.is_a?(Array) ? v.join(',') : v.to_s ("%s=%s" % [uri_encode(k), uri_encode(value)]) unless value.empty? end.compact.join("&") end def uri_encode(item) encoded = URI.encode(item.to_s) encoded.gsub(/\=/, '%3D') end end end
class Product < ApplicationRecord has_many :order_products has_many :orders, through: :order_products def status if is_alive? "在庫中" else "已售完" end end def sell self.count = self.count - 1 end def sold_out self.is_alive = false if self.count == 0 end end
module API module Ver1 class Candidate < Grape::API format :json formatter :json, Grape::Formatter::Jbuilder resource :provision do route_param :provision_id do resource :candidate do # GET /api/ver1/candidate desc 'Return all candidates depends on specific provision.' params do requires :provision_id, type: Integer, desc: 'provision id.' end get '', jbuilder: 'candidate/index' do @candidates = ::Candidate.joins(:user).select("candidates.*, users.name AS user_name").where("provision_id =?",params[:provision_id]) end end end end resource :candidate do # GET /api/ver1/candidate/{:id} desc 'Return a candidate.' params do requires :id, type: Integer, desc: 'candidate id.' end get ':id', jbuilder: 'candidate/show' do @candidate = ::Candidate.joins(:user, :provision).select("candidates.*, users.name AS user_name, provisions.name AS provision_name").find(params[:id]) @users = ::User.joins(:candidate_votes).select("users.*, candidate_votes.created_at AS vote_time").where("candidate_votes.candidate_id = ?", params[:id]) end # Post /api/ver1/candidate desc 'Create a Candidate.' params do requires :name, type: String, desc: 'Candidate name.' requires :provision_id, type: Integer, desc: 'Provision id. Parent of candidate.' requires :note, type: String, desc: 'Candidate note.' end post '', jbuilder: 'candidate/create' do authenticate_user! candidate = ::Candidate.create({ name: params[:name], provision_id: params[:provision_id], user_id: @user.id, note: params[:note], end_date: nil }) if candidate.save # vote yourself candidate_vote = ::CandidateVote.create(:candidate_id=>candidate.id,:user_id=>@user.id) if candidate_vote.save @result= "success" end else @result= "Failed" end end end end end end
require "matrix" class InputParser class << self def call(raw_input, task_number) draw = raw_input[0].split(",") boards = parse_raw_boards_input(raw_input[1..-1], task_number) [draw, boards] end private # This parser is shared among solutions to part 1 and part 2 and the output # is dependent on which part we're solving right now. def parse_raw_boards_input(input, task_number) input.map do |raw_board| rows = raw_board.split("\n").map { |row| row.split(" ") } task_number == :part_1 ? Matrix[*rows] : { input: Matrix[*rows], is_winner: false } end end end end
Rails.application.routes.draw do # root to: 'visitors#index' devise_for :users resources :users resources :posts do member do put "like", to: "posts#upvote" end end root to: 'posts#index' end
class Phrase attr_accessor :words def initialize(words) self.words = words.gsub(/[,.!&@$%^&:(\n)]/, ' ').gsub(/ '|' /, ' ').downcase end def word_count counts = Hash.new(0) words.split.each do |word| counts[word] += 1 end counts end end
# frozen_string_literal: true # The UnderlyingLegInstrumentParser is responsible for the <Undly> mapping. This tag is one of many tags inside # a FIXML message. To see a complete FIXML message there are many examples inside of spec/datafiles. # # Relevant FIXML Slice: # # <Undlys> # <Undly Exch="NYMEX" MMY="201508" SecTyp="FUT" Src="H" ID="CL"/> # </Undlys> # module CmeFixListener # <Undly> Mappings from abbreviations to full names (with types) class UnderlyingLegInstrumentParser extend ParsingMethods MAPPINGS = [ ["legUnderlyingProductCode", "ID"], ["legUnderlyingProductCodeSource", "Src"], ["legUnderlyingSecurityType", "SecTyp"], ["legUnderlyingMaturity", "MMY"], ["legUnderlyingProductExchange", "Exch"] ].freeze end end
require 'test_helper' # Tests for Client summarization, UserFeat top_feats, UserBadge top_badges class SummarizationTest < ActiveSupport::TestCase self.use_instantiated_fixtures = true fixtures :clients fixtures :users def setup # clear all data UserBadge.delete_all UserFeat.delete_all ClientStat.delete_all @c1 = Client.find(@existingbob.id) @c2 = Client.find(@bob.id) @u1 = User.find(@kilgore.id) @u2 = User.find(@chad.id) Time.zone = @c1.time_zone end def test_one_feat UserFeat.create(:user_id => @u1.id, :client_id => @c1.id, :feat_id => @share_trailer.id, :created_at => 1.day.ago) start_time = 1.days.ago.beginning_of_day end_time = 1.days.ago.end_of_day @c1.summarize(start_time, end_time) @c2.summarize(start_time, end_time) # using @c1 timezone, but ok for here t1 = ClientStat.total_stats(@c1, start_time.to_date, end_time.to_date) t2 = ClientStat.total_stats(@c2, start_time.to_date, end_time.to_date) assert_equal t1, {:users => 1, :badges => 0, :feats => 1} assert_equal t2, {:users => 0, :badges => 0, :feats => 0} b1 = UserBadge.top_badges(@c1.id, start_time.to_date, end_time.to_date) b2 = UserBadge.top_badges(@c2.id, start_time.to_date, end_time.to_date) assert_equal b1.length, 0 assert_equal b2.length, 0 f1 = UserFeat.top_feats(@c1.id, start_time.to_date, end_time.to_date) f2 = UserFeat.top_feats(@c2.id, start_time.to_date, end_time.to_date) # using @c1 timezone, but ok for here assert_equal f1.length, 1 assert_equal f2.length, 0 assert_equal f1[0], {:feat_id => @share_trailer.id, :feat_name => @share_trailer.name, :feats => 1} end def test_before_data # should miss UserFeat.create(:user_id => @u1.id, :client_id => @c1.id, :feat_id => @share_trailer.id, :created_at => 1.day.ago) start_time = 2.days.ago.beginning_of_day end_time = 2.days.ago.end_of_day @c1.summarize(start_time, end_time) t1 = ClientStat.total_stats(@c1, start_time.to_date, end_time.to_date) assert_equal t1, {:users => 0, :badges => 0, :feats => 0} end def test_after_data # should miss UserFeat.create(:user_id => @u1.id, :client_id => @c1.id, :feat_id => @share_trailer.id, :created_at => 1.day.ago) start_time = 0.days.ago.beginning_of_day end_time = 0.days.ago.end_of_day @c1.summarize(start_time, end_time) t1 = ClientStat.total_stats(@c1, start_time.to_date, end_time.to_date) assert_equal t1, {:users => 0, :badges => 0, :feats => 0} end def test_multiple_feats # also testing day boundaries ... UserFeat.create(:user_id => @u1.id, :client_id => @c1.id, :feat_id => @share_trailer.id, :created_at => 1.day.ago.end_of_day) UserFeat.create(:user_id => @u1.id, :client_id => @c1.id, :feat_id => @share_trailer.id, :created_at => 1.day.ago.end_of_day) UserFeat.create(:user_id => @u1.id, :client_id => @c1.id, :feat_id => @view_trailer.id, :created_at => 1.day.ago.beginning_of_day) start_time = 1.days.ago.beginning_of_day end_time = 1.days.ago.end_of_day @c1.summarize(start_time, end_time) t1 = ClientStat.total_stats(@c1, start_time.to_date, end_time.to_date) assert_equal t1, {:users => 1, :badges => 0, :feats => 3} b1 = UserBadge.top_badges(@c1.id, start_time.to_date, end_time.to_date) assert_equal b1.length, 0 f1 = UserFeat.top_feats(@c1.id, start_time.to_date, end_time.to_date) assert_equal f1.length, 2 # also testing sorting assert_equal f1[0], {:feat_id => @share_trailer.id, :feat_name => @share_trailer.name, :feats => 2} assert_equal f1[1], {:feat_id => @view_trailer.id, :feat_name => @view_trailer.name, :feats => 1} end def test_multiple_days # also testing day boundaries ... UserFeat.create(:user_id => @u1.id, :client_id => @c1.id, :feat_id => @share_trailer.id, :created_at => 1.day.ago.end_of_day) UserFeat.create(:user_id => @u1.id, :client_id => @c1.id, :feat_id => @share_trailer.id, :created_at => 1.day.ago.beginning_of_day) UserFeat.create(:user_id => @u1.id, :client_id => @c1.id, :feat_id => @view_trailer.id, :created_at => Time.zone.now) start_time = 1.days.ago.beginning_of_day end_time = 0.days.ago.end_of_day @c1.summarize(1.days.ago.beginning_of_day, 1.days.ago.end_of_day) @c1.summarize(0.days.ago.beginning_of_day, 0.days.ago.end_of_day) t1 = ClientStat.total_stats(@c1, start_time.to_date, end_time.to_date) assert_equal t1, {:users => 1, :badges => 0, :feats => 3} b1 = UserBadge.top_badges(@c1.id, start_time.to_date, end_time.to_date) assert_equal b1.length, 0 f1 = UserFeat.top_feats(@c1.id, start_time.to_date, end_time.to_date) assert_equal f1.length, 2 # also testing sorting assert_equal f1[0], {:feat_id => @share_trailer.id, :feat_name => @share_trailer.name, :feats => 2} assert_equal f1[1], {:feat_id => @view_trailer.id, :feat_name => @view_trailer.name, :feats => 1} end def test_one_badge UserBadge.create(:user_id => @u1.id, :client_id => @c1.id, :badge_id => @beginner.id, :created_at => 1.day.ago.end_of_day) start_time = 1.days.ago.beginning_of_day end_time = 1.days.ago.end_of_day @c1.summarize(start_time, end_time) @c2.summarize(start_time, end_time) # using @c1 timezone, but ok for here t1 = ClientStat.total_stats(@c1, start_time.to_date, end_time.to_date) t2 = ClientStat.total_stats(@c2, start_time.to_date, end_time.to_date) assert_equal t1, {:users => 0, :badges => 1, :feats => 0} assert_equal t2, {:users => 0, :badges => 0, :feats => 0} b1 = UserBadge.top_badges(@c1.id, start_time.to_date, end_time.to_date) b2 = UserBadge.top_badges(@c2.id, start_time.to_date, end_time.to_date) assert_equal b1.length, 1 assert_equal b1[0], {:badge_id => @beginner.id, :badge_name => @beginner.name, :badges => 1} assert_equal b2.length, 0 f1 = UserFeat.top_feats(@c1.id, start_time.to_date, end_time.to_date) f2 = UserFeat.top_feats(@c2.id, start_time.to_date, end_time.to_date) # using @c1 timezone, but ok for here assert_equal f1.length, 0 assert_equal f2.length, 0 end def test_multiple_badges # also testing multiple users ... UserBadge.create(:user_id => @u1.id, :client_id => @c1.id, :badge_id => @beginner.id, :created_at => 1.day.ago.end_of_day) UserBadge.create(:user_id => @u2.id, :client_id => @c1.id, :badge_id => @beginner.id, :created_at => 1.day.ago.end_of_day) UserBadge.create(:user_id => @u1.id, :client_id => @c1.id, :badge_id => @advanced.id, :created_at => 1.day.ago.beginning_of_day) start_time = 1.days.ago.beginning_of_day end_time = 1.days.ago.end_of_day @c1.summarize(start_time, end_time) t1 = ClientStat.total_stats(@c1, start_time.to_date, end_time.to_date) assert_equal t1, {:users => 0, :badges => 3, :feats => 0} b1 = UserBadge.top_badges(@c1.id, start_time.to_date, end_time.to_date) assert_equal b1.length, 2 # also testing sorting assert_equal b1[0], {:badge_id => @beginner.id, :badge_name => @beginner.name, :badges => 2} assert_equal b1[1], {:badge_id => @advanced.id, :badge_name => @advanced.name, :badges => 1} f1 = UserFeat.top_feats(@c1.id, start_time.to_date, end_time.to_date) assert_equal f1.length, 0 end def test_time_zone # should miss (Hawaii vs UTC) UserFeat.create(:user_id => @u1.id, :client_id => @c1.id, :feat_id => @share_trailer.id, :created_at => 1.day.ago.beginning_of_day) Time.zone = nil start_time = 1.days.ago.beginning_of_day end_time = 1.days.ago.end_of_day @c1.summarize(start_time, end_time) t1 = ClientStat.total_stats(@c1, start_time.to_date, end_time.to_date) assert_equal t1, {:users => 0, :badges => 0, :feats => 0} end end
class AddDescripcionToNoticiaEscuela < ActiveRecord::Migration[5.1] def change add_column :noticia_escuelas, :descripcion, :string end end
class AddToRecord < ActiveRecord::Migration[5.1] def change add_column :records, :school_year, :integer add_column :records, :teacher_name, :string add_column :records, :position, :string add_column :records, :phone, :string add_column :records, :teacher_email, :string end end
class GuideController < ApplicationController skip_before_filter :authorize def index @restaurants = Restaurant.order(:Name) @list = current_list end end
class RemoveProjectSocialStateFromProject < ActiveRecord::Migration def change remove_column :projects, :project_social_state end end
@boards.each do |board| json.set! board.id do json.extract! board, :id, :title end end
# frozen_string_literal: true # Helper methods for the advanced search form module AdvancedHelper include BlacklightAdvancedSearch::AdvancedHelperBehavior # Overrides method in BlacklightAdvancedSearch::AdvancedHelperBehavior in order to include # Aria describedby on select tag def select_menu_for_field_operator options = { t('blacklight_advanced_search.all') => 'AND', t('blacklight_advanced_search.any') => 'OR' }.sort select_tag(:op, options_for_select(options, params[:op]), class: 'input-small', aria: { describedby: 'advanced-help' }) end end
FactoryBot.define do sequence :email do |n| "email@domain#{n}.com" end sequence :first_name do |n| "FirstName #{n}" end sequence :last_sign_in_at do |n| DateTime.now end sequence :url_slug do |n| "url-slug-#{n}" end sequence :average_rating do rand(1..5) end sequence :rating_count do rand(1..100) end factory :user do first_name { generate :first_name } email { generate :email } last_sign_in_at { generate :last_sign_in_at } password { 'password' } url_slug active { true } terms_and_conditions { true } timezone { 'Central Time (US & Canada)' } # programs = [] # programs << FactoryBot.create(:program) # programs { programs } average_rating { generate :average_rating } rating_count { generate :rating_count } country { "USA" } city { "Boston" } factory :client_user do roles { [ Role.find_or_create_by(name: 'Client') ] } end factory :volunteer_user do roles { [ Role.find_or_create_by(name: 'Volunteer') ] } end end end
FactoryBot.define do factory :order_street do postal_code { "123-4567" } delivery_area_id { 2 } municipality { "横浜市美浜区" } address { "青山1-1-1" } building { "柳ビル" } phone_number { "09012345678" } token { "testtest" } user_id { 1 } item_id { 1 } end end
# frozen_string_literal: true require "#{Rails.root}/lib/next_question_fetcher" module Api module V1 class QuestionsController < ApiController include QuestionConcern before_action :set_question, only: %i(preview) def preview preview_question = {} details = question_details(@question) preview_question = preview_question.merge(question_json(@question)).merge(details: details) render json: { question: preview_question } end private def set_question unless params[:question_id] return _unprocessable_data end @question = Question.find_by(id: params[:question_id].to_i) unless @question _not_found end end end end end
module DataPlugins::Facet class FacetItem < ApplicationRecord include Jsonable include DataPlugins::Facet::Concerns::ActsAsFacetItem include Translatable include FapiCacheable # ASSOCIATIONS belongs_to :facet belongs_to :parent, class_name: FacetItem has_many :sub_items, class_name: FacetItem, foreign_key: :parent_id, dependent: :destroy has_many :facet_item_owners, class_name: FacetItemOwner, dependent: :destroy has_many :events, -> { by_area(Current.user.area) }, through: :facet_item_owners, source: :owner, source_type: 'Event' has_many :orgas, -> { by_area(Current.user.area) }, through: :facet_item_owners, source: :owner, source_type: 'Orga' has_many :offers, -> { by_area(Current.user.area) }, through: :facet_item_owners, source: :owner, source_type: 'DataModules::Offer::Offer' def owners events + orgas + offers end # VALIDATIONS validates :title, length: { maximum: 255 } validates :color, length: { maximum: 255 } validates :facet, presence: true validates :parent_id, presence: true, allow_nil: true validate :validate_facet_and_parent # SAVE HOOKS after_save :move_sub_items_to_new_facet after_save :move_owners_to_new_parent def fapi_cacheable_on_destroy super FapiCacheJob.new.update_all_entries_for_all_areas end # CLASS METHODS class << self def translatable_attributes %i(title) end def translation_key_type 'facet_item' end def attribute_whitelist_for_json default_attributes_for_json.freeze end def default_attributes_for_json %i(title color facet_id parent_id).freeze end def relation_whitelist_for_json default_relations_for_json.freeze end def default_relations_for_json %i(sub_items).freeze end def facet_item_params(params) # facet_id is a route param, hence we introduce new_facet_id to allow facet_id update params.permit(:title, :color, :parent_id, :new_facet_id, :facet_id) end def save_facet_item(params) facet_item = find_or_initialize_by(id: params[:id]) facet_item.assign_attributes(facet_item_params(params)) facet_item.save! facet_item end end def link_owner(owner) if facet_item_owners.where(owner: owner).exists? return false end if !facet_supports_type_of_owner?(owner) return false end FacetItemOwner.create( owner: owner, facet_item_id: id ) # link parent too if parent FacetItemOwner.find_or_create_by( owner: owner, facet_item_id: parent.id ) end true end def unlink_owner(owner) facet_item_owner = facet_item_owners.where(owner: owner).first return false unless facet_item_owner facet_item_owners.delete(facet_item_owner) # unlink subitems too unlink_sub_items(owner) true end def sub_items_to_hash(attributes: nil, relationships: nil) sub_items.map { |item| item.to_hash(attributes: item.class.default_attributes_for_json, relationships: nil) } end def owners_to_hash(attributes: nil, relationships: nil) owners.map { |owner| owner.to_hash } end private def validate_facet_and_parent unless Facet.exists?(facet&.id) return errors.add(:facet_id, 'Kategorie existiert nicht.') end validate_parent_relation # cannot set parent with different facet_id parent = self.class.find_by_id(parent_id) if parent && parent.facet_id != facet_id return errors.add(:parent_id, 'Ein übergeordnetes Attribut muss zur selben Kategorie gehören.') end end def move_sub_items_to_new_facet sub_items.update(facet_id: self.facet_id) end def facet_supports_type_of_owner?(owner) type = owner.class.to_s.split('::').last facet.owner_types.where(owner_type: type).exists? end # ActsAsFacetItem def item_owners(item = nil) item = item || self item.facet_item_owners end def items_of_owners(owner) owner.facet_items end def message_parent_nonexisting 'Übergeordnetes Attribut existiert nicht.' end def message_item_sub_of_sub 'Ein Attribut kann nicht Unterattribut eines Unterattributs sein.' end def message_sub_of_itself 'Ein Attribut kann nicht sein Unterattribut sein.' end def message_sub_cannot_be_nested 'Ein Attribut mit Unterattributen kann nicht verschachtelt werden.' end include DataModules::FeNavigation::Concerns::HasFeNavigationItems end end
require 'helper' require 'sumologic/kubernetes/reader.rb' require 'fluent/test/log' class ReaderTest < Test::Unit::TestCase include SumoLogic::Kubernetes::Connector include SumoLogic::Kubernetes::Reader def setup # runs before each test stub_apis connect_kubernetes end def teardown # runs after each test end def log Fluent::Test::TestLogger.new end test 'fetch_pod is expected' do pod = fetch_pod('sumologic', 'somepod') assert_not_nil pod assert_equal pod['apiVersion'], 'v1' assert_equal pod['kind'], 'Pod' end test 'extract_pod_labels is expected' do pod = fetch_pod('sumologic', 'somepod') assert_not_nil pod labels = extract_pod_labels(pod) assert_not_nil labels assert_equal labels['pod-template-hash'], '1691804713' assert_equal labels['run'], 'curl-byi' end test 'fetch_pod_labels is expected' do labels = fetch_pod_labels('sumologic', 'somepod') assert_not_nil labels assert_equal labels['pod-template-hash'], '1691804713' assert_equal labels['run'], 'curl-byi' end test 'fetch_pod_labels return empty map if resource not found' do labels = fetch_pod_labels('non-exist', 'somepod') assert_not_nil labels assert_equal labels.size, 0 end end
require 'console_creep/stores/store' module ConsoleCreep module Stores class DatabaseStore < Store def store(user, command, result, error) ActiveRecord::Base.logger.silence do record = { user: user, command: command, result: result, error: error } record.delete_if { |k, _v| except_columns.include?(k) } model_name.create(record) end end private def except_columns Array.wrap(options[:except]) end def model_name options[:model].to_s.constantize end end end end
class CreateThingCategoryRelation < ActiveRecord::Migration def change create_table :thing_category_relations do |t| t.references :category, index: true t.references :catable, polymorphic: true, index: true t.boolean :primary t.timestamps null: false end end end
class PaginaPrincipalAdministradorController < ApplicationController before_action :authenticate_administrator! def index @administrator=current_administrator end end
require "rubygems/test" require "rubygems/collection" require "rubygems/info" class TestGemCollection < Gem::Test def test_by a = entry "foo", "1.0.0" b = entry "foo", "2.0.0" c = filter a, b expected = { "foo" => [a, b] } assert_equal expected, c.by(:name) end def test_empty? assert filter.empty? refute filter(:x).empty? end def test_equality a = filter b = filter assert_equal a, b refute_equal a, filter(:x) refute_equal a, a.latest refute_equal a, a.prerelease refute_equal a, a.released end def test_latest a = entry "foo", "1.0.0" b = entry "foo", "2.0.0" c = filter a, b assert_equal [b], c.latest.entries end def test_latest? f = filter f.latest! assert f.latest? end def test_latest! a = entry "foo", "1.0.0" b = entry "foo", "2.0.0" c = filter a, b c.latest! assert_equal [b], c.entries end def test_ordered repo do foo = gem "foo", "1.0.0" do |s| s.add_dependency "bar" end bar = gem "bar", "1.0.0" coll = Gem::Collection.new [foo, bar] assert_equal [bar, foo], coll.ordered end end def test_ordered_cyclic repo do foo = gem "foo", "1.0.0" do |s| s.add_dependency "bar" end bar = gem "bar", "1.0.0" do |s| s.add_dependency "foo" end coll = Gem::Collection.new [foo, bar] assert_equal [foo, bar], coll.ordered end def test_ordered_indirect repo do foo = gem "foo", "1.0.0" bar = gem "bar", "1.0.0" do |s| s.add_dependency "foo" end baz = gem "baz", "1.0.0" do |s| s.add_dependency "bar" s.add_dependency "foo" end coll = Gem::Collection.new [bar, baz, foo] assert_equal [foo, bar, baz], coll.ordered end def test_ordered_versions repo do f1 = gem "foo", "1.0.0" f2 = gem "foo", "2.0.0" bar = gem "bar", "1.0.0" do |s| s.add_dependency "foo", "> 1" end baz = gem "baz", "1.0.0" do |s| s.add_dependency "bar" end coll = Gem::Collection.new [baz, f1, bar, f2] assert_equal [f2, bar, baz, f1], coll.ordered end end end end def test_prerelease a = entry "foo", "1.0.0" b = entry "bar", "1.0.0.pre" c = filter a, b assert_equal [b], c.prerelease.entries end def test_prerelease? f = filter f.prerelease! assert f.prerelease? end def test_prerelease! a = entry "foo", "1.0.0" b = entry "bar", "1.0.0.pre" c = filter a, b c.prerelease! assert_equal [b], c.entries end def test_released a = entry "foo", "1.0.0" b = entry "bar", "1.0.0.pre" c = filter a, b assert_equal [a], c.released.entries end def test_released? f = filter f.released! assert f.released? end def test_released! a = entry "foo", "1.0.0" b = entry "bar", "1.0.0.pre" c = filter a, b c.released! assert_equal [a], c.entries end def test_search a = entry "foo", "1.0.0" b = entry "bar", "1.0.0" specs = filter a, b assert_equal [a], specs.search("foo").entries assert_equal [b], specs.search("bar").entries end def test_search_regexp a = entry "foobar", "1.0.0" b = entry "foobaz", "1.0.0" specs = Gem::Collection.new [a, b] assert_equal [a, b], specs.search(/foo/).sort end def test_search_requirement a = entry "foo", "1.0.0" b = entry "foo", "2.0.0" specs = Gem::Collection.new [a, b] assert_equal [b], specs.search("foo", "> 1.0.0").entries end def test_search_platform a = entry "foo", "1.0.0" b = entry "foo", "1.0.0", "jruby" specs = Gem::Collection.new [a, b] assert_equal [b], specs.search("foo", :platform => "jruby").entries end def test_search_narrowed a = entry "foo", "1.0.0" b = entry "foo", "1.0.0.pre" specs = Gem::Collection.new [a, b] assert_equal [b], specs.prerelease.search("foo").entries end def test_unique a = entry "foo", "1.0.0" b = entry "foo", "1.0.0" c = filter a, b assert_equal [a], c.unique.entries end def test_unique! a = entry "foo", "1.0.0" b = entry "foo", "1.0.0" c = filter a, b c.unique! assert_equal [a], c.entries end def entry name, version, platform = nil Gem::Info.new name, version, platform end def filter *args, &block Gem::Collection.new args, &block end end
Adela::Application.routes.draw do localized do devise_for :users as :user do get 'users/edit' => 'devise/registrations#edit', as: 'edit_user_registration' patch 'users/:id' => 'devise/registrations#update', as: 'user_registration' end get '/:slug/catalogo' => 'organizations#catalog', as: 'organization_catalog' get '/:slug/inventario' => 'organizations#inventory', as: 'organization_inventory' root to: 'home#index' resources :organizations, only: [:show, :update] do get 'profile', on: :member get 'search', on: :collection resources :documents, controller: 'organizations/documents', only: [:index] do put 'update', on: :collection, as: 'update' end resources :catalogs, only: [:index], shallow: true do get 'check', on: :collection put 'publish', on: :member resources :datasets, shallow: true do resources :distributions end end end end resources :catalog_versions, path: 'catalog/versions', only: [:index, :show] namespace :api, defaults: { format: 'json' } do namespace :v1 do get '/catalogs' => 'organizations#catalogs' get '/organizations' => 'organizations#organizations' get '/gov_types' => 'organizations#gov_types' resources :datasets, only: [] do get 'contact_point', on: :member end resources :distributions, only: [:show] resources :organizations, only: [:show] do get 'inventory', on: :member get 'documents', on: :member collection do get 'catalogs' get 'organizations' end end resources :sectors, only: [:index] end end namespace :admin do get '/', to: 'base#index', as: 'root' get 'import_users', to: 'users#import' post 'create_users', to: 'users#create_users' post 'stop_acting', to: 'users#stop_acting' resources :users, except: :show do member do put 'grant_admin_role' put 'remove_admin_role' get 'acting_as' get 'edit_password' put 'update_password' end end resources :organizations, except: [:show, :destroy] do get :edit_multiple, on: :collection put :update_multiple, on: :collection end end namespace :inventories do resources :datasets do get 'confirm_destroy', on: :member resources :distributions do get 'confirm_destroy', on: :member end end end end
module Emarsys module Broadcast class TransactionalXmlBuilder < BaseXmlBuilder def build_xml(transactional) Nokogiri::XML::Builder.new do |xml| xml.mailing do xml.name transactional.name xml.properties { shared_properties(xml, transactional) } xml.recipientFields { transactional.recipient_fields.each do |field| xml.field name: field end } shared_nodes(xml, transactional) end end end end end end
VALID_CHOICES = %w(rock paper scissors).freeze # def test_method(something) # prompt("#{something}") # end def win?(first, second) (first == 'rock' && second == 'scissors') || (first == 'scissors' && second == 'paper') || (first == 'paper' && second == 'rock') end def display_results(player, computer) if win?(player, computer) prompt("YOU WIN! You chose #{player}, and the computer chose #{computer}.") elsif win?(computer, player) prompt("YOU LOST! You chose #{player}, and the computer chose #{computer}.") else prompt("TIE! You chose #{player}, and the computer chose #{computer}.") end end # p test_method('boofar') def prompt(message) puts "=> #{message}" end choice = '' computer_choice = '' loop do loop do prompt("Please choose one: #{VALID_CHOICES.join(', ')}") choice = gets.chomp break if VALID_CHOICES.include?(choice) prompt("Please pick a vaild choice. Check your spelling!") end computer_choice = VALID_CHOICES.sample display_results(choice, computer_choice) prompt("Would you like to play again?") again = gets.chomp break unless again.downcase.start_with?('y') end prompt("Thanks for playing! Good-bye!")
# frozen_string_literal: true module Sourcescrub # Utils module Utils # Veriables module Veriables # Description of operators PEOPLE_ROLES = { 'founder' => 'Founder', 'employee' => 'Employee', 'board_member' => 'Board Member', 'advisor' => 'Advisor' }.freeze end end end
#!/usr/bin/env ruby =begin author: Yuya Nishida <yuya@j96.org> licence: X11 id: $Id: amrit,v 1.3 2002/12/04 04:05:53 yuya Exp $ amrit commands =end module Amrit autoload :VERSION, "amrit/version" def self.run(args) sleep_time = 1 trap(:TERM) do exit(1) end trap(:USR1) do STDERR.puts("failed to run: exec(*#{args.inspect})") exit(2) end loop do fork do begin exec(*args) rescue Process.kill(:USR1, Process.ppid) end end pid, status = *Process.wait2 sleep(sleep_time) end end end Amrit.run(ARGV)
require 'will_paginate/view_helpers/base' require 'will_paginate/view_helpers/link_renderer' # Merb gives you a Merb::Plugins.config hash...feel free to put your stuff in your piece of it Merb::Plugins.config[:paging] = { :class => 'pagination', :previous_label => '&laquo; Previous', :next_label => 'Next &raquo;', :inner_window => 4, # links around the current page :outer_window => 1, # links around beginning and end :separator => ' ', # single space is friendly to spiders and non-graphic browsers :param_name => :page, :params => nil, :renderer => 'WillPaginate::ViewHelpers::LinkRenderer', :page_links => true, :container => true } WillPaginate::ViewHelpers::LinkRenderer.class_eval do protected def url(page) params = @template.request.params.except(:action, :controller).merge('page' => page) @template.url(:this, params) end end Merb::AbstractController.send(:include, WillPaginate::ViewHelpers::Base)
def line(arr) if arr.length == 0 puts "The line is currently empty." else new_arr = [] arr.each.with_index(1) do |name, i| new_arr << " #{i}. #{name}" end puts "The line is currently:#{new_arr.join}" end end def take_a_number(arr,name) puts "Welcome, #{name}. You are number #{arr.length + 1} in line." arr << name end def now_serving(arr) if arr.length == 0 puts "There is nobody waiting to be served!" else puts "Currently serving #{arr.shift}." end end
class CreateBrandCategories < ActiveRecord::Migration def self.up create_table :brand_categories do |t| t.string :name end BrandCategory.create(:name => "Fortune 1000 Company") end def self.down drop_table :brand_categories end end
class Condition < Base attr_accessor :treatments self.query = <<-EOL PREFIX foaf: <http://xmlns.com/foaf/0.1> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX stories: <http://purl.org/ontology/stories/> PREFIX foaf: <http://xmlns.com/foaf/0.1/> PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX ho: <http://www.bbc.co.uk/ontologies/health/> CONSTRUCT { ?con rdf:type ho:Condition . ?con rdfs:label ?conLabel . ?eff ho:treats ?con . ?int ho:efficacy ?eff . ?int rdfs:label ?intLabel . } WHERE { ?con rdf:type ho:Condition . ?con rdfs:label ?conLabel . OPTIONAL { ?eff ho:treats ?con . ?int ho:efficacy ?eff . ?int rdfs:label ?intLabel . }} EOL def self.find_all graph = self.retrieve conditions_index_query = RDF::Query.new({ :condition => { RDF.type => RDF::URI('http://www.bbc.co.uk/ontologies/health/Condition'), RDF::URI('http://www.w3.org/2000/01/rdf-schema#label') => :label } }) conditions = [] conditions_index_query.execute(graph).each do |result| conditions << Condition.new(:uri => result.condition, :label => result.label) end conditions end def self.find(id) self.validate_guid(id) resource = RDF::URI(RESOURCE_BASE + id + '#id') Rails.logger.info "Finding #{id}" graph = self.retrieve conditions_index_query = RDF::Query.new do |query| query << [resource, RDF.type, RDF::URI('http://www.bbc.co.uk/ontologies/health/Condition')] query << [:efficacy, RDF::URI('http://www.bbc.co.uk/ontologies/health/treats'), resource] query << [resource, RDF::URI('http://www.w3.org/2000/01/rdf-schema#label'), :label] end conditions = [] conditions_index_query.execute(graph).each do |condition| # Now find what treats this condition treats_index_query = RDF::Query.new do |query| query << [condition.efficacy, RDF::URI('http://www.bbc.co.uk/ontologies/health/treats'), resource] query << [:intervention, RDF::URI('http://www.bbc.co.uk/ontologies/health/efficacy'), condition.efficacy] end interventions = [] treats_index_query.execute(graph).each do |treat| interventions << Intervention.new(:uri => treat.intervention).load end return Condition.new( :uri => resource, :label => condition.label, :treatments => interventions ) end return nil end def initialize(params = {}) super [:treatments].each do |attr| send("#{attr}=", params[attr]) if params.key?(attr) end end def load graph = Condition.retrieve query = RDF::Query.new do |query| query << [uri, RDF::URI('http://www.w3.org/2000/01/rdf-schema#label'), :label] end query.execute(graph).each do |condition| self.label = condition.label end self end end
include Java import java.awt.BasicStroke module ScorchedEarth module Renders class Mouse attr_reader :mouse, :player def initialize(mouse, player) @mouse = mouse @player = player end def call(graphics, color_palette) return unless mouse.x && mouse.y color = color_palette.get(player.x) height = graphics.destination.height graphics.set_color color graphics.setStroke BasicStroke.new 3 graphics.draw_line mouse.x, mouse.y, player.x, height - player.y end end end end
class Producer < ActiveRecord::Base has_and_belongs_to_many :users has_many :webhooks, :through => :consumers has_many :consumers, :dependent => :destroy validates_presence_of :owner_id validates_presence_of :name before_create :make_admin_user def make_admin_user user = User.find( self.owner_id ) self.users << user end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) Product.destroy_all User.destroy_all Role.destroy_all r1 = Role.create({name: "Seller", description: "Can read and create items. Can update and destroy own items"}) r2 = Role.create({name: "Admin", description: "Can perform any CRUD operation on any resource"}) u1 = User.create({name: "Daniel", email: "daniel@gmail.com", password: "12345678", password_confirmation: "12345678", role_id: r1.id}) u2 = User.create({name: "Sue", email: "sue@example.com", password: "aaaaaaaa", password_confirmation: "aaaaaaaa", role_id: r1.id}) u3 = User.create({name: "Kev", email: "kev@example.com", password: "aaaaaaaa", password_confirmation: "aaaaaaaa", role_id: r1.id}) u4 = User.create({name: "Jack", email: "jack@example.com", password: "aaaaaaaa", password_confirmation: "aaaaaaaa", role_id: r2.id}) p1 = Product.create({name: "Rayban Sunglasses", description: "Stylish shades", state: false, price: 99.99, user_id: u1.id}) p2 = Product.create({name: "Gucci watch", description: "Expensive timepiece", state: false, price: 199.99, user_id: u1.id}) p3 = Product.create({name: "Henri Lloyd Pullover", description: "Classy knitwear", state: false, price: 299.99, user_id: u1.id}) p4 = Product.create({name: "Porsche socks", description: "Cosy footwear", state: false, price: 399.99, user_id: u1.id}) p5 = Product.create({name: "Rayban Sunglasses", description: "Stylish shades", state: false, price: 99.99, user_id: u2.id}) p6 = Product.create({name: "Gucci watch", description: "Expensive timepiece", state: false, price: 199.99, user_id: u2.id}) p7 = Product.create({name: "Henri Lloyd Pullover", description: "Classy knitwear", state: false, price: 299.99, user_id: u2.id}) p8 = Product.create({name: "Porsche socks", description: "Cosy footwear", state: false, price: 399.99, user_id: u2.id})
module BoatsHelper def boat_title(boat) "#{boat.manufacturer_model} for sale" end def boat_length(boat, unit = nil) return nil if !boat.length_m || boat.length_m <= 0 unit ||= try(:current_length_unit) || 'm' length = unit == 'ft' ? boat.length_ft.round : boat.length_m.round "#{length}&nbsp;#{unit}".html_safe end def converted_size(size, unit = nil) return nil if !size size = size.to_f return nil if size <= 0 unit ||= try(:current_length_unit) || 'm' size = unit == 'ft' ? size.m_to_ft.round : size "#{size}&nbsp;#{unit}".html_safe end def boat_price(boat, target_currency = nil) if boat.poa? I18n.t('poa') else target_currency ||= current_currency || Currency.default price = Currency.convert(boat.price, boat.safe_currency, target_currency) number_to_currency(price, unit: target_currency.symbol, precision: 0) end end def boat_price_with_converted(boat) converted_price = boat_price(boat, current_currency) if boat.currency && boat.currency != current_currency "#{boat_price(boat, boat.currency)} (#{converted_price})" else converted_price end end def favourite_link_to(boat) favourited = boat.favourited_by?(current_user) fav_class = favourited ? 'fav-link active' : 'fav-link' fav_title = favourited ? 'Unfavourite' : 'Favourite' link_to 'Favourite', "#favourite-#{boat.id}", id: "favourite-#{boat.id}", class: fav_class, title: fav_title, data: {'boat-id' => boat.id, toggle: 'tooltip', placement: 'top'} end def boat_specs(boat) spec_names = %w(beam_m draft_m draft_max draft_min drive_up engine_count berths_count cabins_count hull_material engine keel keel_type) spec_value_by_name = boat.boat_specifications.not_deleted.custom_specs_hash(spec_names) ret = [] ret[0] = [] ret[0] << ['Make', link_to(boat.manufacturer.name, sale_manufacturer_path(manufacturer: boat.manufacturer))] ret[0] << ['Model', link_to(boat.model.name, sale_manufacturer_path(manufacturer: boat.manufacturer, models: boat.model.id))] ret[0] << ['LOA', boat_length(boat), 'loa'] ret[0] << ['Beam', converted_size(spec_value_by_name['beam_m'])] if spec_value_by_name['draft_max'] ret[0] << ['Draft Max', converted_size(spec_value_by_name['draft_max'])] else ret[0] << ['Draft Max', converted_size(spec_value_by_name['draft_m'])] end if spec_value_by_name['draft_min'] ret[0] << ['Draft Min', converted_size(spec_value_by_name['draft_min'])] elsif spec_value_by_name['drive_up'] ret[0] << ['Draft Min', converted_size(spec_value_by_name['drive_up'])] end ret[0] << ['Keel', spec_value_by_name['keel'] || spec_value_by_name['keel_type']] ret[0] << ['Hull Material', spec_value_by_name['hull_material']] ret[0] << ['Boat Type', boat.boat_type&.name_stripped&.titleize] ret[0] << ['RB Ref', boat.ref_no] ret[1] = [] ret[1] << ['Price', boat_price_with_converted(boat), 'price'] ret[1] << ['Tax Status', boat.tax_status] ret[1] << ['Year', boat.year_built] ret[1] << ['Engine Make', boat.engine_manufacturer&.name || spec_value_by_name['engine']] ret[1] << ['Engine Model', boat.engine_model&.name] ret[1] << ['Engine Count', spec_value_by_name['engine_count']] ret[1] << ['Fuel', boat.fuel_type&.name] ret[1] << ['Cabins', spec_value_by_name['cabins_count']] ret[1] << ['Berths', spec_value_by_name['berths_count']] ret[1] << ['Location', boat.location] if boat.country ret[1] << ['Country', link_to(boat.country.name, sale_manufacturer_path(manufacturer: boat.manufacturer, models: boat.model.id, country: boat.country.slug))] end ret.each { |col| col.select! { |pair| !pair[1].blank? } } end def implicit_boats_count(count) count >= 10000 ? '10,000 plus' : count end def boats_index_filters_data @top_manufacturer_infos = Manufacturer.joins(:boats).where(boats: {status: 'active'}) .group('manufacturers.name, manufacturers.slug') .order('COUNT(*) DESC').limit(60) .pluck('manufacturers.name, manufacturers.slug, COUNT(*)').sort_by!(&:first) @boat_types = BoatType.joins(:boats).where(boats: {status: 'active'}) .group('boat_types.name, boat_types.slug') .order('boat_types.name') .select('boat_types.name, boat_types.slug, COUNT(*) AS boats_count') @countries = Country.joins(:boats).where(boats: {status: 'active'}) .group('countries.name, countries.slug') .order('countries.name') .select('countries.name, countries.slug, COUNT(*) AS boats_count') end end
class ProductReviewsController < ApplicationController before_filter :login_required # GET /product_reviews # GET /product_reviews.xml def index @product_reviews = ProductReview.find(:all) respond_to do |format| format.html # index.rhtml format.xml { render :xml => @product_reviews.to_xml } end end # GET /product_reviews/1 # GET /product_reviews/1.xml def show @product_review = ProductReview.find(params[:id]) respond_to do |format| format.html # show.rhtml format.xml { render :xml => @product_review.to_xml } end end # GET /product_reviews/new def new @product_review = ProductReview.new end # GET /product_reviews/1;edit def edit @product_review = ProductReview.find(params[:id]) end # POST /product_reviews # POST /product_reviews.xml def create @product_review = ProductReview.new(params[:product_review]) respond_to do |format| if @product_review.save flash[:notice] = 'ProductReview was successfully created.' format.html { redirect_to product_review_url(@product_review) } format.xml { head :created, :location => product_review_url(@product_review) } else format.html { render :action => "new" } format.xml { render :xml => @product_review.errors.to_xml } end end end # PUT /product_reviews/1 # PUT /product_reviews/1.xml def update @product_review = ProductReview.find(params[:id]) respond_to do |format| if @product_review.update_attributes(params[:product_review]) flash[:notice] = 'ProductReview was successfully updated.' format.html { redirect_to product_review_url(@product_review) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @product_review.errors.to_xml } end end end # DELETE /product_reviews/1 # DELETE /product_reviews/1.xml def destroy @product_review = ProductReview.find(params[:id]) @product_review.destroy respond_to do |format| format.html { redirect_to product_reviews_url } format.xml { head :ok } end end end
class AlphaSmsStatusJob include Sidekiq::Worker include Sidekiq::Throttled::Worker sidekiq_options queue: :default sidekiq_options retry: 3 sidekiq_throttle( threshold: {limit: 250, period: 1.minute} ) def perform(request_id) detailable = AlphaSmsDeliveryDetail.find_by!(request_id: request_id) response = Messaging::AlphaSms::Api.new.get_message_status_report(request_id) raise_api_errors(request_id, response) delivery_status_data = response.dig("data", "recipients").first["status"] detailable.request_status = delivery_status_data if delivery_status_data detailable.save! end def raise_api_errors(request_id, response) error = response["error"] unless error.zero? raise Messaging::AlphaSms::Error.new("Error fetching message status for #{request_id}: #{error}") end end end
# -*- mode: ruby -*- # vi: set ft=ruby : # user configurable settings require './settings' Vagrant.configure("2") do |config| # use ubuntu precise pangolin 32 bit config.vm.box = VAGRANT_BOX # use SYNCED_DIRS in `settings.rb' to mirror directories on the host system to # the vm filesystem SYNCED_DIRS.each do |dir| config.vm.synced_folder dir.first, dir.last end # use ssh_agent to forward keys so private keys for github etc don't need # to be provisioned config.ssh.forward_agent = true # provision via chef_solo config.vm.provision :chef_solo do |chef| chef.add_recipe "base" chef.add_recipe "elixir" chef.json = { "base" => { "user" => GIT_USER, "email" => GIT_EMAIL } } end end
module Configuration class Invalid < RuntimeError def initialize(message) super(message + " for environment #{ENV['RACK_ENV']}") end end def after_config_loaded(method_name=nil, &block) after_config_loaded_callbacks.push(block || -> { send(method_name) }) end def config=(config) @config = config after_config_loaded_callbacks.each(&:call) end def config return @config if @config reload_config end def reload_config(path=File.expand_path("../config.yml", File.dirname(__FILE__)), env=ENV['RACK_ENV']) all_configs = YAML.load_file(path) self.config = all_configs[env] end # force config to be loaded. def configure! config end protected def after_config_loaded_callbacks @after_config_loaded_callbacks ||= [] end end
# require "rubygems" # require "bundler" require 'pry' # Bundler.require :default, :test include Rake::DSL prompt = "irb" cfg = YAML.load_file File.expand_path("../config/application.yml", __FILE__) if defined? pry prompt = "pry" end def relative_dir path File.expand_path "../#{path}", __FILE__ end task default: :help task :help do puts <<HELP Available rake tasks: rake console - Run a #{prompt} console with all environment loaded. rake rerun - Start a rerun server. rake start_server - Start the Sinatra server. rake kill_server - Kill the Sinatra server. rake restart_server - Restart the Sinatra server. HELP end desc "Run a #{prompt} console with all environment loaded." task :console do puts "Loading console..." sh "#{prompt} -r #{relative_dir "app.rb"}" end namespace :server do desc "Start a rerun server." task :rerun do puts "Starting rerun..." sh "rerun -b -- thin start" end desc "Start the sinatra server" task :start do puts "Starting server..." sh "thin start -S tmp/#{cfg["app_name"]}.sock" end desc "Kill the Sinatra server." task :kill do sh "kill -s INT \`cat #{relative_dir "tmp/pids/thin.pid"}\`" end desc "Restart the Sinatra server." task :restart do Rake::Task['server:kill'].invoke Rake::Task['server:start'].invoke end end
class CreateApps < ActiveRecord::Migration def up create_table :apps do |t| t.string 'uuid', :null => false t.string 'appname', :null => false t.string 'apptype', :null => false t.string 'consumer_key', :null => false t.string 'consumer_secret', :null => false t.string 'user_id', :null => false t.timestamps end end def down drop_table :apps end end
#!/usr/bin/env ruby # frozen_string_literal: true # rubocop:disable all require 'diplomatic_bag' require 'optparse' require 'diplomat/version' def syntax printf "USAGE: #{$PROGRAM_NAME} [[action]] [[options]]\n\n" \ "\t#{$PROGRAM_NAME} services list [options]\n" \ "\t#{$PROGRAM_NAME} service status <service-name> [options]\n" \ "\t#{$PROGRAM_NAME} info [options]\n" \ "\t#{$PROGRAM_NAME} nodes list-duplicate-id [options]\n" \ "\t#{$PROGRAM_NAME} version\n\n" \ "Options:\n" \ "\t-a, --http-addr\t\tThe `address` and port of the Consul HTTP agent\n" \ "\t-d, --datacenter\tName of the datacenter to query\n" \ "\t-f, --format\t\tOutput format (json|text)\n" \ "\t-t, --token\t\tACL token to use in the request\n" exit 0 end def launch_query(arguments, options) case arguments[0] when 'services' if arguments[1] == 'list' DiplomaticBag.get_all_services_status(options) else syntax exit 0 end when 'service' if arguments[1] == 'status' DiplomaticBag.get_services_info(arguments[2], options) else syntax exit 0 end when 'info' DiplomaticBag.consul_info(options) when 'nodes' if arguments[1] == 'list-duplicate-id' DiplomaticBag.get_duplicate_node_id(options) else syntax exit 0 end when 'version' puts Diplomat::VERSION exit 0 else syntax exit 0 end end def parse_as_text(input, indent) case input when Array input.each do |v| parse_as_text(v, indent) end when Hash input.each do |k, v| print "#{indent}#{k}:\n" parse_as_text(v, indent+' ') end else print "#{indent}#{input}\n" end end options = {http_addr: ENV['CONSUL_HTTP_ADDR'] || 'localhost:8500'} params = {} output = {} OptionParser.new do |opts| opts.banner = "USAGE: #{$PROGRAM_NAME} -a [[action]] [[options]]" opts.on('-h', '--help', 'Show help') do syntax end opts.on("-a", "--http-addr [CONSUL_URL]", "The `address` and port of the Consul HTTP agent") do |server| options[:http_addr] = server end opts.on("-d", "--datacenter [DATACENTER]", "Name of the datacenter to query (services option)") do |dc| params[:dcs] = dc end opts.on("-f", "--format TYPE", [:json, :txt], "Output format") do |format| params[:format] = format end opts.on("-t", "--token [TOKEN]", "ACL token to use in the request") do |token| options[:token] = token end end.parse! options[:http_addr] = "http://#{options[:http_addr]}" unless options[:http_addr].start_with? 'http' if params[:dcs] dcs = DiplomaticBag.get_datacenters_list(params[:dcs].split(','), options) dcs.each do |dc| options[:dc] = dc output[dc] = launch_query(ARGV, options) end else output = launch_query(ARGV, options) end case params[:format] when :json puts JSON.pretty_generate(output) unless output == {} else parse_as_text(output, '') unless output == {} end # rubocop:enable all
class CreateTransferRequest def initialize(participant:, receiver:) @participant = participant @receiver = receiver end def call transfer_request = TransferRequest.new( participant: participant, receiver: receiver, contact: receiver_contact ) if transfer_request.save NotifyTransferRequestUser.new(transfer_request).call else Result.failure("Failed to create transfer request") end end private attr_reader :participant, :receiver def receiver_contact Contact.from(phone_number: participant.phone_number, user: receiver) end end
#-- # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #++ require 'omniauth-oauth2' module OmniAuth module Strategies class SurveyMonkey < OmniAuth::Strategies::OAuth2 option :client_options, { :site => 'https://api.surveymonkey.net', :authorize_url => '/oauth/authorize', :token_url => '/oauth/token' } option :name, 'surveymonkey' option :access_token_options, { :header_format => 'Bearer %s', :param_name => 'access_token' } option :authorize_options, [:scope] uid { raw_info['id'] } info do prune!( 'username' => raw_info['username'], 'account_type' => raw_info['account_type'], 'email' => raw_info['email'], 'id' => raw_info['id'] ) end extra do prune!(raw_info) end def raw_info @raw_info ||= access_token.get('/v3/users/me').parsed end def authorize_params super.tap do |params| params.merge!(:state => request.params['state']) if request.params['state'] end end def callback_url full_host + script_name + callback_path end private def prune!(hash) hash.delete_if do |_, value| prune!(value) if value.is_a?(Hash) value.nil? || (value.respond_to?(:empty?) && value.empty?) end end end end end OmniAuth.config.add_camelization 'surveymonkey', 'SurveyMonkey'
require './car.rb' require './parkinglot.rb' describe ParkingLot do let(:parking_lot) { ParkingLot.new(6) } it 'should accept slots in parking lot' do expect(parking_lot.counter).to eq(6) end describe '.full' do it 'should return false if the counter is not null or 0' do expect(parking_lot.full?).to eq(false) end it 'should return true is the available slots is zero' do parking_lot.counter = 0 expect(parking_lot.full?).to eq(true) end end describe '.park' do it 'should accept car with number and color and store in parking lot' do expect { parking_lot.park('KA 01 EA 0001', 'White') } .to change { parking_lot.counter }.by(-1) end end describe '.leave' do it 'should be able to leave the lot and make free space in lot' do slot_number = parking_lot.park('KA 01 EA 0002', 'White') expect { parking_lot.leave(slot_number) } .to change { parking_lot.counter }.by(1) end it 'should return false if the slot is empty' do expect(parking_lot.leave(5)).to eq(false) end end describe '.slot_numbers_for_cars_with_colour' do it 'should provide slot numbers alloted for car with given color' do slot_number = parking_lot.park('KA 01 EA 0002', 'White') expect(parking_lot.slot_numbers_for_cars_with_colour('White')) .to eq(slot_number.to_s) end end describe '.slot_number_for_registration_number' do it 'should provide slot number based on reg number' do slot_number = parking_lot.park('KA 01 EA 0002', 'White') expect(parking_lot.slot_number_for_registration_number('KA 01 EA 0002')) .to eq(slot_number) end it 'should return not found if invalid number is passed' do expect(parking_lot.slot_number_for_registration_number('KA 01 EA 0004')) .to eq('Not found') end end describe '.registration_numbers_for_cars_with_colour' do it 'should provide reg number of car with given colour' do parking_lot.park('KA 01 EA 0002', 'White') expect(parking_lot.registration_numbers_for_cars_with_colour('White')) .to eq('KA 01 EA 0002') end end describe '.status' do it 'should provide current status of lot in table' do parking_lot.park('KA 01 EA 0003', 'White') expect(parking_lot.status).not_to be_nil end end end
module BookKeeping VERSION = 2 end class FoodChain FIRST_SENTENCE = "I know an old lady who swallowed a ".freeze FORE_LAST_SENTENCE = "\nI don't know why she swallowed the fly. Perhaps she'll die.\n\n".freeze LAST_SENTENCE = "I know an old lady who swallowed a horse.\nShe's dead, of course!\n" COMMENTS = [ "\nI don't know how she swallowed a cow!", "\nJust opened her throat and swallowed a goat!", "\nWhat a hog, to swallow a dog!", "\nImagine that, to swallow a cat!", "\nHow absurd to swallow a bird!", "\nIt wriggled and jiggled and tickled inside her.", "" ] REFRAINS = [ "\nI don't know how she swallowed a cow.", "\nShe swallowed the cow to catch the goat.", "\nShe swallowed the goat to catch the dog.", "\nShe swallowed the dog to catch the cat.", "\nShe swallowed the cat to catch the bird.", "\nShe swallowed the bird to catch the spider that wriggled and jiggled and tickled inside her.", "\nShe swallowed the spider to catch the fly.", ] def self.song song = "" 6.downto(0) do |index| song << FIRST_SENTENCE + REFRAINS[index].split.last.sub('her', 'spider') song << COMMENTS[index] index.upto(6) do |counter_index| song << REFRAINS[counter_index+1].to_s end song << FORE_LAST_SENTENCE end song << LAST_SENTENCE end end
require "./spec/spec_helper" describe "EntityDefinition" do before do @subject = CDM::EntityDefinition end it "exists" do @subject.should be end describe ".create_entity" do before do @dummy = @subject.new end context "when adding the :foo entity with no attributes" do before do @dummy.create_entity :foo do |e| end end it "has an entities collection of length 1" do @dummy.entities.length.should eq 1 end it "has an entity named 'Foo'" do @dummy.entities.first.name.should eq "Foo" end end context "when adding the :person entity with a few attributes" do before do @dummy.create_entity :person do |e| e.string :name, optional: "NO" e.int16 :age end end it "has an entities collection of length 1" do @dummy.entities.length.should eq 1 end it "has an entity named 'Person'" do @dummy.entities.first.name.should eq "Person" end it "has the 'name' attribute in the first entity" do @dummy.entities.first.fields.first.name.should eq "name" end end context "when adding three entities" do before do @dummy.create_entity :foo do |e| e.string :foo_attribute e.date :foo_date_attribute e.int16 :foo_int_attribute end @dummy.create_entity :bar do |e| e.binary :bar_binary_attribute e.boolean :bar_boolean_attribute e.float :bar_float_attribute end @dummy.create_entity :baz do |e| e.transformable :baz_transformable_attribute e.decimal :baz_decimal_attribute end end it "has 3 entities in the colection" do @dummy.entities.length.should eq 3 end it "has the Foo entity in the first spot of the collection" do @dummy.entities.first.name.should eq "Foo" end end end describe ".xml_attributes" do before do @dummy = @subject.new end it "returns 9 attributes" do @dummy.xml_attributes.keys.length.should eq 9 end context "default values" do before do @result = @dummy.xml_attributes end it "returns empty string for name" do @result[:name].should eq "" end it "returns empty string for userDefinedModelVersionIdentifier" do @result[:userDefinedModelVersionIdentifier].should eq "" end it "returns 'com.apple.IDECoreDataModeler.DataModel' for type" do @result[:type].should eq "com.apple.IDECoreDataModeler.DataModel" end it "returns '1.0' for documentVersion" do @result[:documentVersion].should eq "1.0" end it "returns '2061' for documentVersion" do @result[:lastSavedToolsVersion].should eq "2061" end it "returns '12D78 for systemVersion'" do @result[:systemVersion].should eq "12D78" end it "returns 'Automatic for minimumToolsVersion'" do @result[:minimumToolsVersion].should eq "Automatic" end it "returns 'Automatic for macOSVersion'" do @result[:macOSVersion].should eq "Automatic" end it "returns 'Automatic for iOSVersion'" do @result[:iOSVersion].should eq "Automatic" end end context "custom values" do before do @dummy.name = "Lorem Ipsum" @dummy.document_version = "2.4" @result = @dummy.xml_attributes end it "returns 'Lorem Ipsum' for name" do @result[:name].should eq "Lorem Ipsum" end it "returns '2.4' for documentVersion" do @result[:documentVersion].should eq "2.4" end end end describe ".to_xml" do before do class ModelDefinition < CDM::EntityDefinition def define_model create_entity :foo do |e| e.string :foo_string e.date :foo_date e.int16 :foo_int end create_entity :bar do |e| e.binary :bar_binary e.boolean :bar_boolean e.float :bar_float end create_entity :baz do |e| e.transformable :baz_transformable e.decimal :baz_decimal end end end @model_definition = ModelDefinition.new @model_definition.define_model @xml_array = @model_definition.to_xml.split("\n") end it "contains entity name 'Foo' in the line at index 2" do @xml_array[2].should eq ' <entity name="Foo" representedClassName="Foo" syncable="YES">' end end end
class RemoveShowCoursesFromSurvey < ActiveRecord::Migration def change remove_column :surveys, :show_courses end end
module Validation def self.included(receiver) receiver.extend ClassMethods receiver.send :include, InstanceMethods end module ClassMethods attr_reader :validators def validate(attribute, *params) @validators ||= [] @validators << { attribute => params } end end module InstanceMethods def validate! self.class.validators.each do |validator| validator.each do |attribute, params| attr_value = instance_variable_get("@#{attribute}".to_sym) send(params[0], attr_value, params[1]) end end true end def valid? validate! rescue StandardError false end private def presence(value, option) raise 'Не может быть пустым!' if value.strip.empty? || value.nil? end def format(value, option) raise 'Не соответствует формат!' if value !~ option end def type(value, option) raise 'Не соответствует тип!' unless value.is_a? option end end end
class CreateTooms < ActiveRecord::Migration[6.0] def change create_table :tooms do |t| t.timestamps end end end
require 'rails_helper' feature "regular user updates registration" do context "they change their name and email" do before(:each) do regular_user = FactoryBot.create(:user) sign_in regular_user visit root_path click_on "edit account" fill_in "Name", with: "somebody else" fill_in "Email", with: "somebody_else@example.com" fill_in "Current password", with: "#{regular_user.password}" click_on "Update" end scenario "they see a flash message" do expect(page).to have_content("Your account has been updated successfully") end scenario "they see that they are logged in with their new name" do expect(page).to have_content("somebody else") end scenario "they see their account credentials change" do click_on "edit" expect(page).to have_field('user_name', with: "somebody else") expect(page).to have_field('user_email', with: "somebody_else@example.com") end end context "they change their password successfully" do before(:each) do @regular_user = FactoryBot.create(:user) sign_in @regular_user visit edit_user_registration_path fill_in "Password", with: "testpassword2" fill_in "Password confirmation", with: "testpassword2" fill_in "Current password", with: @regular_user.password click_on "Update" end scenario "they see a flash message" do expect(page).to have_content("Your account has been updated successfully") end scenario "they are able to sign in with their new password" do sign_out @regular_user visit root_path click_on "sign in" fill_in "Email", with: @regular_user.email fill_in "Password", with: "testpassword2" click_on "Sign in" expect(page).to have_content("somebody") end end end
class AddRoleToMembershipAndRemoveGroupCreatorAndGroupAdmin < ActiveRecord::Migration def self.up add_column :memberships, :role, :string, :default => "member" remove_column :memberships, :group_creator remove_column :memberships, :group_admin end def self.down remove_column :memberships, :role add_column :memberships, :group_creator, :boolean, :default => false add_column :memberships, :group_admin, :boolean, :default => false end end
class AddTextAndPagesToDocuments < ActiveRecord::Migration def change add_column :documents, :text, :text add_column :documents, :pages, :json end end
module SyntaxHighlighting # A child object to `Pattern`; repesenting a captures from a tmLanguage file. # class Captures def initialize(contents) @store = {} contents.each do |number_identifier, values| raise UnhandledCapturesError if values["name"].nil? @store[number_identifier.to_i] = values["name"].to_sym end end # - block: yields Integer, String # def each(&blk) @store.each(&blk) end def [](index) @store[index] end def inspect @store.inspect end def to_s inspect end end end
# frozen_string_literal: true require 'spec_helper' RSpec.describe Brcobranca::CalculoData do it 'Calcula o fator de vencimento' do expect((Date.parse '2008-02-01').fator_vencimento).to eq('3769') expect((Date.parse '2008-02-02').fator_vencimento).to eq('3770') expect((Date.parse '2008-02-06').fator_vencimento).to eq('3774') expect((Date.parse '03/07/2000').fator_vencimento).to eq('1000') expect((Date.parse '04/07/2000').fator_vencimento).to eq('1001') expect((Date.parse '05/07/2000').fator_vencimento).to eq('1002') expect((Date.parse '01/05/2002').fator_vencimento).to eq('1667') expect((Date.parse '17/11/2010').fator_vencimento).to eq('4789') expect((Date.parse '21/02/2025').fator_vencimento).to eq('9999') expect((Date.parse '22/02/2025').fator_vencimento).to eq('1000') expect((Date.parse '23/02/2025').fator_vencimento).to eq('1001') end it 'Formata a data no padrão visual brasileiro' do expect((Date.parse '2008-02-01').to_s_br).to eq('01/02/2008') expect((Date.parse '2008-02-02').to_s_br).to eq('02/02/2008') expect((Date.parse '2008-02-06').to_s_br).to eq('06/02/2008') end it 'Calcula data juliana' do expect((Date.parse '2009-02-11').to_juliano).to eql('0429') expect((Date.parse '2008-02-11').to_juliano).to eql('0428') expect((Date.parse '2009-04-08').to_juliano).to eql('0989') # Ano 2008 eh bisexto expect((Date.parse '2008-04-08').to_juliano).to eql('0998') end end
class CreateCategoria < ActiveRecord::Migration[6.1] def change create_table :categoria do |t| t.string :nombre t.string :descripcion t.string :img t.timestamps t.column :deleted_at, :datetime, :limit => 6 end end end
module Recliner class ViewDocument < Recliner::Document property :language, String, :default => 'javascript' property :views, Map(String => View) def update_views(new_views) self.views = views.dup.replace(new_views) save! if changed? end def invoke(view, *args) views[view].invoke(database, "#{id}/_view/#{view}", *args) rescue DocumentNotFound # The view disappeared from the database while we were working with the view document. # Reset the revision, save the view document, and try to invoke the view again. self.rev = nil save! and retry end end end
class Course < ActiveRecord::Base attr_accessible :name # a student can e on many courses, a course can have many students has_and_belongs_to_many :students end
# == Schema Information # # Table name: calendar_dates # # id :integer not null, primary key # calendar_id :integer # date_fr :datetime # date_to :datetime # created_at :datetime not null # updated_at :datetime not null # class CalendarDate < ActiveRecord::Base attr_accessible :date_fr, :date_to belongs_to :calendar DATE_INT = { 'January' => 1, 'February' => 2, 'March' => 3, 'April' => 4, 'May' => 5, 'June' => 6, 'July' => 7, 'August' => 8, 'September' => 9, 'October' => 10, 'November' => 11, 'December' => 12 } def self.featured where('DATE(date_fr) >= CURRENT_DATE AND DATE(date_fr) <= ADDDATE(CURRENT_DATE, 7)') end def self.this_month where('LEFT(CURRENT_DATE(), 7) = LEFT(date_fr, 7) OR LEFT(CURRENT_DATE(), 7) = LEFT(date_to, 7)') end def self.incoming where('DATE(date_fr) >= CURRENT_DATE AND DATE(date_fr) <= ADDDATE(CURRENT_DATE, 31)') end end
module Hydramata module Works module DatastreamParsers # Responsible for parsing a very simplistic XML document. module SimpleXmlParser module_function def match?(options = {}) datastream = options[:datastream] return false unless datastream if datastream.mimeType =~ /\A(application|text)\/xml/ self else false end end def call(content, &block) require 'nokogiri' doc = Nokogiri::XML.parse(content) doc.xpath('/fields/*').each do |node| block.call(predicate: node.name, value: node.text) end end end end end end
#!/usr/bin/ruby require 'nventory' nvclient = NVentory::Client.new subnet_results = nvclient.get_objects('subnets', {}, {}) if subnet_results.nil? || subnet_results.empty? abort "Failed to get subnet data from nVentory" end subnet_results.each_value do |subnet| if subnet['network'] && subnet['netmask'] @contents << "#{subnet['network']}\t#{subnet['netmask']}" << "\n" end end
class Person < ActiveRecord::Base has_many :addresses, dependent: :destroy has_one :profile, dependent: :destroy accepts_nested_attributes_for :addresses validates :name, :lastname, presence: {message: "No debe estar vacio"} validates :ci, numericality: {only_integer: true, greater_than: 99999, less_than:35000000} validate :check_year, unless: "birthday.nil?" before_save :normalize def self.dame_by_name(name) where(name: name) end def full_name [name, lastname].join(" ") end private def normalize self.class.attribute_names.each do |attr| self.send(attr).upcase! if self.send(attr).class == String end end def check_year if birthday.year > 2000 errors.add(:birthday, "Debe ser mayor") end end end
########################################################################## # Copyright 2017 ThoughtWorks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ########################################################################## require 'rails_helper' describe ApiV3::Admin::PluginInfosController do include ApiHeaderSetupTeardown include ApiV3::ApiVersionHelper before(:each) do @default_plugin_info_finder = double('default_plugin_info_finder') allow(controller).to receive('default_plugin_info_finder').and_return(@default_plugin_info_finder) @default_plugin_manager = double('default_plugin_manager') allow(controller).to receive('default_plugin_manager').and_return(@default_plugin_manager) notification_view = com.thoughtworks.go.plugin.domain.common.PluginView.new('role_config_view_template') metadata = com.thoughtworks.go.plugin.domain.common.Metadata.new(true, false) @plugin_settings = com.thoughtworks.go.plugin.domain.common.PluggableInstanceSettings.new([com.thoughtworks.go.plugin.domain.common.PluginConfiguration.new('memberOf', metadata)], notification_view) end describe "security" do describe "show" do it 'should allow anyone, with security disabled' do disable_security expect(controller).to allow_action(:get, :show) end it 'should disallow non-admin user, with security enabled' do enable_security login_as_user expect(controller).to disallow_action(:get, :show, {:id => 'plugin_id'}).with(401, 'You are not authorized to perform this action.') end it 'should allow admin users, with security enabled' do login_as_admin expect(controller).to allow_action(:get, :show) end it 'should allow pipeline group admin users, with security enabled' do login_as_group_admin expect(controller).to allow_action(:get, :show) end end describe "index" do it 'should allow anyone, with security disabled' do disable_security expect(controller).to allow_action(:get, :index) end it 'should disallow non-admin user, with security enabled' do enable_security login_as_user expect(controller).to disallow_action(:get, :index).with(401, 'You are not authorized to perform this action.') end it 'should allow admin users, with security enabled' do login_as_admin expect(controller).to allow_action(:get, :index) end it 'should allow pipeline group admin users, with security enabled' do login_as_group_admin expect(controller).to allow_action(:get, :index) end end end describe "index" do before(:each) do login_as_group_admin end it 'should list all plugin_infos' do vendor = GoPluginDescriptor::Vendor.new('bob', 'https://bob.example.com') about = GoPluginDescriptor::About.new('Foo plugin', '1.2.3', '17.2.0', 'Does foo', vendor, ['Linux']) descriptor = GoPluginDescriptor.new('foo.example', '1.0', about, nil, nil, false) plugin_info = com.thoughtworks.go.plugin.domain.notification.NotificationPluginInfo.new(descriptor, @plugin_settings) expect(@default_plugin_info_finder).to receive(:allPluginInfos).with(nil).and_return([plugin_info]) get_with_api_header :index expect(response).to be_ok expect(actual_response).to eq(expected_response([plugin_info], ApiV3::Plugin::PluginInfosRepresenter)) end it 'should list bad plugins when `include_bad` param is true' do good_vendor = GoPluginDescriptor::Vendor.new('bob', 'https://bob.example.com') good_about = GoPluginDescriptor::About.new('Good plugin', '1.2.3', '17.2.0', 'Does foo', good_vendor, ['Linux']) good_plugin = GoPluginDescriptor.new('good.plugin', '1.0', good_about, nil, nil, false) good_plugin_info = com.thoughtworks.go.plugin.domain.notification.NotificationPluginInfo.new(good_plugin, nil) bad_vendor = GoPluginDescriptor::Vendor.new('bob', 'https://bob.example.com') bad_about = GoPluginDescriptor::About.new('Foo plugin', '1.2.3', '17.2.0', 'Does foo', bad_vendor, ['Linux']) bad_plugin = GoPluginDescriptor.new('bad.plugin', '1.0', bad_about, nil, nil, false) bad_plugin.markAsInvalid(%w(foo bar), java.lang.RuntimeException.new('boom!')) bad_plugin_info = com.thoughtworks.go.plugin.domain.common.BadPluginInfo.new(bad_plugin) expect(@default_plugin_manager).to receive(:plugins).and_return([bad_plugin, good_plugin]) expect(@default_plugin_info_finder).to receive(:allPluginInfos).with(nil).and_return([good_plugin_info]) get_with_api_header :index, include_bad: true expect(response).to be_ok expect(actual_response).to eq(expected_response([good_plugin_info, bad_plugin_info], ApiV3::Plugin::PluginInfosRepresenter)) end it 'should filter plugin_infos by type' do vendor = GoPluginDescriptor::Vendor.new('bob', 'https://bob.example.com') about = GoPluginDescriptor::About.new('Foo plugin', '1.2.3', '17.2.0', 'Does foo', vendor, ['Linux']) descriptor = GoPluginDescriptor.new('foo.example', '1.0', about, nil, nil, false) plugin_info = com.thoughtworks.go.plugin.domain.notification.NotificationPluginInfo.new(descriptor, @plugin_settings) expect(@default_plugin_info_finder).to receive(:allPluginInfos).with('scm').and_return([plugin_info]) get_with_api_header :index, type: 'scm' expect(response).to be_ok expect(actual_response).to eq(expected_response([plugin_info], ApiV3::Plugin::PluginInfosRepresenter)) end it 'should filter unsupported plugin extensions' do vendor = GoPluginDescriptor::Vendor.new('bob', 'https://bob.example.com') about = GoPluginDescriptor::About.new('Foo plugin', '1.2.3', '17.2.0', 'Does foo', vendor, ['Linux']) descriptor = GoPluginDescriptor.new('foo.example', '1.0', about, nil, nil, false) notification_plugin_info = com.thoughtworks.go.plugin.domain.notification.NotificationPluginInfo.new(descriptor, @plugin_settings) analytics_plugin_info = com.thoughtworks.go.plugin.domain.analytics.AnalyticsPluginInfo.new(descriptor, nil, nil, nil) expect(@default_plugin_info_finder).to receive(:allPluginInfos).with('scm').and_return([notification_plugin_info, analytics_plugin_info]) get_with_api_header :index, type: 'scm' expect(response).to be_ok expect(actual_response).to eq(expected_response([notification_plugin_info], ApiV3::Plugin::PluginInfosRepresenter)) end it 'should not filter supported plugin extensions' do vendor = GoPluginDescriptor::Vendor.new('bob', 'https://bob.example.com') about = GoPluginDescriptor::About.new('Foo plugin', '1.2.3', '17.2.0', 'Does foo', vendor, ['Linux']) descriptor = GoPluginDescriptor.new('foo.example', '1.0', about, nil, nil, false) allPluginInfos = [com.thoughtworks.go.plugin.domain.analytics.AnalyticsPluginInfo.new(descriptor, nil, nil, nil), com.thoughtworks.go.plugin.domain.authorization.AuthorizationPluginInfo.new(descriptor, nil, nil, nil, nil), com.thoughtworks.go.plugin.domain.configrepo.ConfigRepoPluginInfo.new(descriptor, @plugin_settings), com.thoughtworks.go.plugin.domain.elastic.ElasticAgentPluginInfo.new(descriptor, nil, nil, nil, nil), com.thoughtworks.go.plugin.domain.notification.NotificationPluginInfo.new(descriptor, @plugin_settings), com.thoughtworks.go.plugin.domain.packagematerial.PackageMaterialPluginInfo.new(descriptor, nil, nil, nil), com.thoughtworks.go.plugin.domain.pluggabletask.PluggableTaskPluginInfo.new(descriptor, nil, nil), com.thoughtworks.go.plugin.domain.scm.SCMPluginInfo.new(descriptor, nil, nil, nil)] expect(@default_plugin_info_finder).to receive(:allPluginInfos).and_return(allPluginInfos) get_with_api_header :index expected_response = %w(authorization configrepo elastic-agent notification package-repository scm task) expect(response).to be_ok expect(actual_response[:_embedded][:plugin_info].length).to eq(7) expect(actual_response[:_embedded][:plugin_info].map {|pi| pi['type']}.sort).to eq(expected_response) end it 'should be a unprocessible entity for a invalid plugin type' do expect(@default_plugin_info_finder).to receive(:allPluginInfos).with('invalid_type').and_raise(InvalidPluginTypeException.new) get_with_api_header :index, type: 'invalid_type' expect(response.code).to eq('422') json = JSON.parse(response.body).deep_symbolize_keys expect(json[:message]).to eq('Your request could not be processed. Invalid plugins type - `invalid_type` !') end describe "route" do describe "with_header" do it 'should route to the index action of plugin_infos controller' do expect(:get => 'api/admin/plugin_info').to route_to(action: 'index', controller: 'api_v3/admin/plugin_infos') end end describe "without_header" do before :each do teardown_header end it 'should not route to index action of plugin_infos controller without header' do expect(:get => 'api/admin/plugin_info').to_not route_to(action: 'index', controller: 'api_v3/admin/plugin_infos') expect(:get => 'api/admin/plugin_info').to route_to(controller: 'application', action: 'unresolved', url: 'api/admin/plugin_info') end end end end describe "show" do before(:each) do login_as_group_admin end it 'should fetch a plugin_info for the given id' do vendor = GoPluginDescriptor::Vendor.new('bob', 'https://bob.example.com') about = GoPluginDescriptor::About.new('Foo plugin', '1.2.3', '17.2.0', 'Does foo', vendor, ['Linux']) descriptor = GoPluginDescriptor.new('foo.example', '1.0', about, nil, nil, false) plugin_info = com.thoughtworks.go.plugin.domain.notification.NotificationPluginInfo.new(descriptor, @plugin_settings) expect(@default_plugin_info_finder).to receive(:pluginInfoFor).with('plugin_id').and_return(plugin_info) get_with_api_header :show, id: 'plugin_id' expect(response).to be_ok expect(actual_response).to eq(expected_response(plugin_info, ApiV3::Plugin::PluginInfoRepresenter)) end it 'should fetch a bad plugin info if plugin is bad' do bad_vendor = GoPluginDescriptor::Vendor.new('bob', 'https://bob.example.com') bad_about = GoPluginDescriptor::About.new('Foo plugin', '1.2.3', '17.2.0', 'Does foo', bad_vendor, ['Linux']) bad_plugin = GoPluginDescriptor.new('bad.plugin', '1.0', bad_about, nil, nil, false) bad_plugin.markAsInvalid(%w(foo bar), java.lang.RuntimeException.new('boom!')) bad_plugin_info = com.thoughtworks.go.plugin.domain.common.BadPluginInfo.new(bad_plugin) expect(@default_plugin_info_finder).to receive(:pluginInfoFor).with('bad.plugin').and_return(nil) expect(@default_plugin_manager).to receive(:getPluginDescriptorFor).with('bad.plugin').and_return(bad_plugin) get_with_api_header :show, id: 'bad.plugin' expect(response).to be_ok expect(actual_response).to eq(expected_response(bad_plugin_info, ApiV3::Plugin::PluginInfoRepresenter)) end it 'should return 404 for unsupported plugins' do descriptor = GoPluginDescriptor.new('unsupported.plugin', '1.0', nil, nil, nil, false) analytics_plugin_info = com.thoughtworks.go.plugin.domain.analytics.AnalyticsPluginInfo.new(descriptor, nil, nil, nil) expect(@default_plugin_info_finder).to receive(:pluginInfoFor).with('unsupported.plugin').and_return(analytics_plugin_info) get_with_api_header :show, id: 'unsupported.plugin' expect(response.code).to eq('404') end it 'should return 404 in absence of plugin_info' do expect(@default_plugin_info_finder).to receive(:pluginInfoFor).with('plugin_id').and_return(nil) expect(@default_plugin_manager).to receive(:getPluginDescriptorFor).with('plugin_id').and_return(nil) get_with_api_header :show, id: 'plugin_id' expect(response.code).to eq('404') json = JSON.parse(response.body).deep_symbolize_keys expect(json[:message]).to eq('Either the resource you requested was not found, or you are not authorized to perform this action.') end describe "route" do describe "with_header" do it 'should route to the show action of plugin_infos controller for alphanumeric plugin id' do expect(:get => 'api/admin/plugin_info/foo123bar').to route_to(action: 'show', controller: 'api_v3/admin/plugin_infos', id: 'foo123bar') end it 'should route to the show action of plugin_infos controller for plugin id with hyphen' do expect(:get => 'api/admin/plugin_info/foo-123-bar').to route_to(action: 'show', controller: 'api_v3/admin/plugin_infos', id: 'foo-123-bar') end it 'should route to the show action of plugin_infos controller for plugin id with underscore' do expect(:get => 'api/admin/plugin_info/foo_123_bar').to route_to(action: 'show', controller: 'api_v3/admin/plugin_infos', id: 'foo_123_bar') end it 'should route to the show action of plugin_infos controller for plugin id with dots' do expect(:get => 'api/admin/plugin_info/foo.123.bar').to route_to(action: 'show', controller: 'api_v3/admin/plugin_infos', id: 'foo.123.bar') end it 'should route to the show action of plugin_infos controller for capitalized plugin id' do expect(:get => 'api/admin/plugin_info/FOO').to route_to(action: 'show', controller: 'api_v3/admin/plugin_infos', id: 'FOO') end end describe "without_header" do before :each do teardown_header end it 'should not route to show action of plugin_infos controller without header' do expect(:get => 'api/admin/plugin_info/abc').to_not route_to(action: 'show', controller: 'api_v3/admin/plugin_infos') expect(:get => 'api/admin/plugin_info/abc').to route_to(controller: 'application', action: 'unresolved', url: 'api/admin/plugin_info/abc') end end end end end
class SessionsController < ApplicationController def new @title = "Sign in" end def create user= User.authenticate(params[:session][:email], params[:session][:password]) if user.nil? flash.now[:error] = "Invalid email/password combination." @title="Sign in" render 'new' elsif user.active sign_in user redirect_back_or user else flash.now[:error] = "Account has not yet been verified. Please check your email to activate account." UserMailer.registration_confirmation(user).deliver @title = "Sign in" render 'new' end end def destroy sign_out redirect_to root_path end def recovery begin key= Crypto.decrypt(params[:id]).split(/:/) user = User.find_by_id(key[0],:conditions => {:salt => key[1]}) if user.nil? flash.now[:error] = "The recover link given is not valid." @title="Sign in" render 'new' else sign_in user params[:id] = key[0] flash[:notice] = "Please change your password" redirect_to "/users/#{key[0]}/edit" end rescue ActiveRecord::RecordNotFound flash[:notice] = "The recover link given is not valid" redirect_to(root_url) end end def activation #verify the activation link #get user #activate user #sign in user #redirect to home page begin key= Crypto.decrypt(params[:id]).split(/:/) user = User.find_by_id(key[0],:conditions => {:salt => key[1]}) if user.nil? flash.now[:error] = "The activation link given is not valid." @title="Sign in" render 'new' else user.activate sign_in user params[:id] = key[0] flash[:success] = "Thank you for activating your account!" redirect_to root_path end rescue ActiveRecord::RecordNotFound flash[:notice] = "The activation link given is not valid" redirect_to(root_url) end end end
class AddApplicantorIdToPaymentLogs < ActiveRecord::Migration def change add_column :payment_logs, :applicantor_id, :integer end end
require 'test_helper' class BudgetpostTest < ActiveSupport::TestCase def setup @user = users(:michael) # This code is not idiomatically correct. @budgetpost = @user.budgetposts.build(content: "Lorem ipsum") end test "should be valid" do assert @budgetpost.valid? end test "user id should be present" do @budgetpost.user_id = nil assert_not @budgetpost.valid? end test "content should be present" do @budgetpost.content = " " assert_not @budgetpost.valid? end test "order should be most recent first" do assert_equal budgetposts(:most_recent), Budgetpost.first end end
class CommitmentsController < ApplicationController load_and_authorize_resource def create @commitment = Commitment.new(commitment_params) # We can grab user_id and event_id because we passed them into the params # in the new commitment form (in the event show page). @event = Event.find(params[:event_id]) @user = current_user @host = @event.host # Ensuring the instantiated commitment is attributed to the correct event # and the correct user (the current_user) @commitment.event_id = @event.id @commitment.user_id = @user.id if @commitment.save redirect_to user_event_path(@host, @event), notice: "POP POP" else redirect_to user_event_path(@host, @event, commitment_errors: @commitment.errors.messages), notice: "Error joining event, try again!" end end def destroy @commitment = Commitment.find(params[:id]) @commitment.destroy redirect_to events_path, notice: "Party Poopr" end def update @commitment = Commitment.find(params[:id]) @event = Event.find(params[:event_id]) @commitment.event_id = @event.id @commitment.user_id = current_user.id @host = @commitment.event.host if @commitment.update_attribute(:party_size, commitment_params[:party_size]) redirect_to user_event_path(@host, @commitment.event), notice: "Party size successfully modified!" else redirect_to user_event_path(@host, @commitment.event), notice: "Error, try again!" end end private def commitment_params params.require(:commitment).permit(:party_size, :event_id, :user_id) end end
class User < ActiveRecord::Base has_many :posts has_many :comments, through: :posts has_many :photos end class Post < ActiveRecord::Base validates_length_of :body, maximum: 150 belongs_to :user has_many :comments end class Comment < ActiveRecord::Base belongs_to :user belongs_to :post end class Photo < ActiveRecord::Base belongs_to :user has_many :photos end class Video < ActiveRecord::Base belongs_to :user has_many :videos end
class Shop < ActiveRecord::Base attr_accessible :name has_many :owners has_many :repairs, :through => :owners end
class Ray attr_accessor :origin, :destination def initialize(origin = Vector3.new(0, 0, 0), destination = Vector3.new(0, 0 ,0)) @origin, @destination = origin, destination end def collision_line_segment?(a, b, o, p) ab = Vector3.new(b.x - a.x, b.y - a.y) ap = Vector3.new(p.x - a.x, p.y - a.y) ao = Vector3.new(o.x - a.x, o.y - a.y) if ((ab.x * ap.y - ab.y * ap.x) * (ab.x * ao.y - ab.y * ao.x) <= 0) return true else return false end end def collision_segment_segment?(a, b, o, p) return false if !collision_line_segment?(a, b, o, p) return false if !collision_line_segment?(o, p, a, b) return true end def collides_with_aabb?(aabb) a, b = Vector3.new(@origin.x, @origin.z), Vector3.new(@destination.x, @destination.z) # top segment o, p = Vector3.new(aabb.position.x, aabb.position.z), Vector3.new(aabb.position.x + aabb.size.x, aabb.position.z) return true if collision_segment_segment?(a, b, o, p) # bottom segment o, p = Vector3.new(aabb.position.x, aabb.position.z + aabb.size.z), Vector3.new(aabb.position.x + aabb.size.x, aabb.position.z + aabb.size.z) return true if collision_segment_segment?(a, b, o, p) # left segment o, p = Vector3.new(aabb.position.x, aabb.position.z), Vector3.new(aabb.position.x, aabb.position.z + aabb.size.z) return true if collision_segment_segment?(a, b, o, p) # right segment o, p = Vector3.new(aabb.position.x + aabb.size.x, aabb.position.z), Vector3.new(aabb.position.x + aabb.size.x, aabb.position.z + aabb.size.z) return true if collision_segment_segment?(a, b, o, p) return false end def raytrace x0, x1 = @origin.x / 16.0, @destination.x / 16.0 y0, y1 = @origin.z / 16.0, @destination.z / 16.0 dx = (x1 - x0).abs dy = (y1 - y0).abs x = x0.floor.to_i y = y0.floor.to_i n = 1 x_inc, y_inc, error = nil, nil, nil if (dx == 0) x_inc = 0 error = Float::INFINITY elsif (x1 > x0) x_inc = 1 n += x1.floor.to_i - x error = (x0.floor + 1 - x0) * dy else x_inc = -1 n += x - x1.floor.to_i error = (x0 - x0.floor) * dy end if (dy == 0) y_inc = 0; error -= Float::INFINITY elsif (y1 > y0) y_inc = 1 n += y1.floor.to_i - y error -= (y0.floor + 1 - y0) * dx else y_inc = -1; n += y - y1.floor.to_i error -= (y0 - y0.floor) * dx end path = Array.new while n > 0 # step by step from origin tile to destination tile # to do : handle ennemies, blocks... path << [x.floor, y.floor] if (error > 0) y += y_inc error -= dx else x += x_inc error += dy end n -= 1 end return path end def draw(color) glColor3ub(*color) glLineWidth(5.0) glBegin(GL_LINES) glVertex3i(@origin.x, @origin.y, @origin.z) glVertex3i(@destination.x, @destination.y, @destination.z) glEnd end end
require 'rails_helper' RSpec.feature "User/Visitor navigates to Art home page", type: :feature, js: true do before :each do @user = User.create! username:"Test User", password: "Password" @user.arts.create!( name: "In Thought", image: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRxAKQ_Wafp303ZqqiDhz7bd9sfyWvCHraaRw&usqp=CAU", description: "Picasso Painting" ) end scenario "They can see art that has been uploaded by users on the home page" do visit homepage_path expect(page).to have_content('In Thought') expect(page).to have_content('Picasso Painting') expect(page).to have_css 'div.img-index' puts page.html save_screenshot end end
class Api::BikesController < ApplicationController def index @bikes = Bike.all render json: @bikes end def show @bike = Bike.find(params['id']) render :show end def search @bikes = filter_bikes(filter_options) render json: @bikes end private def bike_params params.require(:bike).permit(:model, :make, :lat, :lng); end def filter_bikes(filter_data) binds = { lat_min: filter_data['lat'][0], lat_max: filter_data['lat'][1], lng_min: filter_data['lng'][0], lng_max: filter_data['lng'][1], start_date: filter_data['start_date'], start_time: filter_data['start_time'], end_date: filter_data['end_date'], end_time: filter_data['end_time'] } bikes = find_available_bikes(binds) end def find_available_bikes(binds) requests = BikeRentalRequest.where.not(<<-SQL, binds) ( (start_date > :end_date) OR (end_date < :start_date) ) SQL binds[:ids] = requests.map{|request| request.bike_id}.uniq find_bikes_in_view(binds) end def find_bikes_in_view(binds) if binds[:lng_min].to_f > binds[:lng_max].to_f in_view_bikes = Bike.where.not(id: binds[:ids]).where(<<-SQL, binds) bikes.lng BETWEEN :lng_min AND 180 OR bikes.lng BETWEEN -180 AND :lng_max SQL else in_view_bikes = Bike.where.not(id: binds[:ids]).where(<<-SQL, binds) bikes.lat BETWEEN :lat_min AND :lat_max AND bikes.lng BETWEEN :lng_min AND :lng_max SQL end end def filter_options options = params[:filter_data] || {} defaults = { 'lat' => [37.67767358309138, 37.8887756788066], 'lng' => [-122.56501542968749, -122.26838457031249] } defaults.merge(options) end end
class HomeController < ApplicationController def index if current_user @posts = Post.all else @posts = Post.where(:active => true) end end end
class AddPushedOutToWorkorders < ActiveRecord::Migration def change add_column :workorders, :showappointment, :boolean end end
class Greeter def initialize(phrase, enabled = true) @phrase = phrase @enabled = enabled end def say_hello(name) "#{@phrase} #{name}" if @enabled end end
module Neo4j module Migrations module Schema class << self def fetch_schema_data(session) {constraints: fetch_constraint_descriptions(session).sort, indexes: fetch_index_descriptions(session).sort} end def synchronize_schema_data(session, schema_data, remove_missing) queries = [] queries += drop_and_create_queries(fetch_constraint_descriptions(session), schema_data[:constraints], remove_missing) queries += drop_and_create_queries(fetch_index_descriptions(session), schema_data[:indexes], remove_missing) session.queries do queries.each { |query| append query } end end private def fetch_constraint_descriptions(session) session.query('CALL db.constraints()').map(&:description) end def fetch_index_descriptions(session) session.query('CALL db.indexes()').reject do |row| # These indexes are created automagically when the corresponding constraints are created row.type == 'node_unique_property' end.map(&:description) end def drop_and_create_queries(existing, specified, remove_missing) [].tap do |queries| if remove_missing (existing - specified).each { |description| queries << "DROP #{description}" } end (specified - existing).each { |description| queries << "CREATE #{description}" } end end end end end end
require 'test_helper' class Sampling::ProgramTest < ActiveSupport::TestCase fixtures :zip_codes test "participant export to csv" do participant_count = 3 program = create_sampling_program('Export Program', participant_count, true) Reputable::Badging.stub!(:best_for, :return => Reputable::Badge.new(:name => 'Foo')) csv_string = program.export_participants_to_csv lines = csv_string.split("\n") # check the basics assert_equal participant_count+1, lines.size assert_match /^Participant ID,Screen Name,Email,First Name,Last Name,Address Line 1,Address Line 2,City,State,Zip Code/, lines[0] assert_match /question,2,Total Weight,New Member,Most Recent Review At,Reputation Level$/, lines[0] lines.shift lines.each_with_index do |line,i| r = i+1 assert_match /^\d+,sampling#{r},email#{r}@example.com,first_name#{r},last_name#{r},address_line_1#{r},address_line_2#{r},city#{r},state#{r},77701,answer#{r},#{r},#{2*r},#{r.even? ? 'y' : 'n'},#{r.even? ? '""' : '2010-01-15 15:00:00'},Foo/, line end end test "recipient import from csv" do program = create_sampling_program 'Import Program', participant_count=3 not_a_user_email = "notauser@example.com" non_participant = Factory.create :user # generate test import file import_file_path = Tempfile.new('sampling_recipient_import').path File.open(import_file_path, 'w') do |f| program.participants.each do |p| f.puts p.user.email end f.puts not_a_user_email f.puts non_participant.email end # import and check results stats = program.import_recipients(import_file_path) assert stats[:imported_count] == participant_count assert stats[:no_user].size == 1 assert stats[:no_user][0] == not_a_user_email assert stats[:no_participant].size == 1 assert stats[:no_participant][0] == non_participant.email assert program.participants.sample_recipients.count == participant_count end private def create_sampling_program(title, participant_count, with_questions=false) product = Factory.create(:product, :title => 'sampling product') program = Factory.create(:sampling_program, :name => 'name', :affiliate_program => Factory.create(:affiliate_program)) program.products << product create_question_answers(program, participant_count) if with_questions 1.upto(participant_count).collect {|i| create_sampling_participant(program, i) } program end def create_question_answers(program, answer_count) question = Factory.create :sampling_program_question, :program => program, :text => 'question', :weight => 2, :position => 1 1.upto(answer_count).collect do |i| opts = {:program_question => question, :text => "answer#{i}", :weight => i, :position => i} Factory.create(:sampling_program_question_answer, opts) end end def create_sampling_participant(program, i) p = Factory.create :sampling_program_participant, :program => program, :participant => Factory.create(:sampling_participant, :user => Factory.create(:user, :screen_name => "sampling#{i}", :email => "email#{i}@example.com", :zip_code => '77701', :created_at => (i.even? ? Time.now : 1.day.ago), :user_stat => Factory.create(:user_stat, :most_recent_review_at => (i.even? ? nil : Time.parse('2010-01-15 15:00:00')) ) ), :first_name => "first_name#{i}", :last_name => "last_name#{i}", :address_line_1 => "address_line_1#{i}", :address_line_2 => "address_line_2#{i}", :city => "city#{i}", :state => "state#{i}", :zip_code => '77701' ) Factory.create(:affiliate_user, :user => p.participant.user, :affiliate_program => program.affiliate_program) if i.even? if !program.program_questions.blank? question = program.program_questions[0] question.user_answer(p.participant.user, question.program_question_answers[i-1]) end p end end
class Country < ApplicationRecord has_many :states, dependent: :destroy #validations validates_presence_of :name, :country_code end
class Admin::CategoriesController < ApplicationController http_basic_authenticate_with name: "jungle", password: "book" def index @categories = Category.order(id: :desc).all end def new @category = Category.new end def create @category = Category.new(category_params) if @category.save redirect_to [:admin, :categories], notice: 'Categories created!' else render :new end end def category_params params.require(:category).permit( :name ) end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :stuffs , dependent: :destroy has_many :tags , dependent: :destroy has_many :stuffs_tags ,through: :tags ,dependent: :destroy after_create :add_preset_tags private def add_preset_tags @user = User.find(self.id) Tag::PRESET_TAGS.each do |t| @user.tags.create!(name: t) end end end
# frozen_string_literal: true module Dynflow module Semaphores class Abstract # Tries to get ticket from the semaphore # Returns true if thing got a ticket # Rturns false otherwise and puts the thing into the semaphore's queue def wait(thing) raise NotImplementedError end # Gets first object from the queue def get_waiting raise NotImplementedError end # Checks if there are objects in the queue def has_waiting? raise NotImpelementedError end # Returns n tickets to the semaphore def release(n = 1) raise NotImplementedError end # Saves the semaphore's state to some persistent storage def save raise NotImplementedError end # Tries to get n tickets # Returns n if the semaphore has free >= n # Returns free if n > free def get(n = 1) raise NotImplementedErrorn end # Requests all tickets # Returns all free tickets from the semaphore def drain raise NotImplementedError end end end end
require 'test_helper' class TestRescues < Test::Unit::TestCase def setup @client = MockMogileFsClient.new end def test_debug_mode app_with :path => %r{^/assets/*}, :debug => true assert_raises(MogileFS::UnreachableBackendError) do get '/assets/unreachable.txt' end end def test_unreachable_exception app_with :path => %r{^/assets/*} get '/assets/unreachable.txt' assert_status 503 assert_body "couldn't connect to mogilefsd backend" end def test_unknown_key_exception @client.expects(:get_file_data).raises(MogileFS::Backend::UnknownKeyError) app_with :path => %r{^/assets/*}, :client => @client get '/assets/unknown.txt' assert_status 404 end def test_mogilefs_exception @client.expects(:get_file_data).raises(MogileFS::Error) app_with :path => %r{^/assets/*}, :client => @client get '/assets/error.txt' assert_status 500 end end
require File.join(File.dirname(__FILE__), 'spec_helper') require 'schematron-nokogiri' describe SchematronNokogiri::Schema do it "should load a schema from a libxml document" do file = File.join "spec", "schema", "pim.sch" doc = Nokogiri::XML(File.open(file)) lambda { SchematronNokogiri::Schema.new doc }.should_not raise_error end it "should validate a good instance doc" do schema_file = File.join 'spec', 'schema', 'fda_sip.sch' instance_file = File.join 'spec', 'instances', 'daitss-sip', 'Example1.xml' schema_doc = Nokogiri::XML(File.open(schema_file)) instance_doc = Nokogiri::XML(File.open(instance_file)) stron = SchematronNokogiri::Schema.new schema_doc results = stron.validate instance_doc results.should be_empty end it "should detect errors for a bad document" do schema_file = File.join 'spec', 'schema', 'fda_sip.sch' instance_file = File.join 'spec', 'instances', 'daitss-sip', 'Example2.xml' schema_doc = Nokogiri::XML(File.open(schema_file)) instance_doc = Nokogiri::XML(File.open(instance_file)) stron = SchematronNokogiri::Schema.new schema_doc results = stron.validate instance_doc results.should_not be_empty end it "should detect errors for a bad ubl" do schema_file = File.join 'spec', 'schema', 'ubl.sch' instance_file = File.join 'spec', 'instances', 'ubl', 'ubl.xml' schema_doc = Nokogiri::XML(File.open(schema_file)) instance_doc = Nokogiri::XML(File.open(instance_file)) stron = SchematronNokogiri::Schema.new schema_doc results = stron.validate instance_doc results.should_not be_empty end it "should log report rules in the results" do schema_file = File.join 'spec', 'schema', 'pim.sch' instance_file = File.join 'spec', 'instances', 'daitss-sip', 'Example1.xml' schema_doc = Nokogiri::XML(File.open(schema_file)) instance_doc = Nokogiri::XML(File.open(instance_file)) stron = SchematronNokogiri::Schema.new schema_doc results = stron.validate instance_doc results.length.should == 1 results.first[:rule_type].should == 'report' end end
module Carbide class Builder attr_reader :manager def initialize(manager) @manager = manager end def build_task(name, context, &block) task = manager[name] if task.nil? task = Task.new(manager, name) manager.register(task) end if block_given? action = Action.new(context, &block) task.enhance(action) end task end def build_pre_task(name, pre_name, context, &block) pre_task = manager[pre_name] if pre_task.nil? pre_task = Task.new(manager, pre_name) manager.register(pre_task) end if block_given? action = Action.new(context, &block) pre_task.enhance(action) end task = manager[name] task.prepend(pre_task) pre_task end def build_post_task(name, post_name, context, &block) post_task = manager[post_name] if post_task.nil? post_task = Task.new(manager, post_name) manager.register(post_task) end if block_given? action = Action.new(context, &block) post_task.enhance(action) end task = manager[name] task.append(post_task) post_task end end end
class Train attr_accessor :wagons_count, :speed, :route attr_reader :type def initialize(train_number, type, wagons_count) @train_number = train_number @type = type @wagons_count = wagons_count @speed = 0 end def move(speed) self.speed = speed end def stop self.speed = 0 end def add_wagon self.wagons_count = wagons_count + 1 if speed.zero? end def delete_wagon self.wagons_count = wagons_count - 1 if speed.zero? end def set_route(route) self.route = route @route_index = 0 current_station.add_train(self) end def forward current_station.delete_train(self) @route_index += 1 current_station.add_train(self) end def backward current_station.delete_train(self) @route_index -= 1 current_station.add_train(self) end def current_station route.stations[@route_index] end def prev_station route.stations[@route_index - 1] end def next_station route.stations[@route_index + 1] end end
#============================================================================== # ** Game_ActionResult #------------------------------------------------------------------------------ # This class handles the results of battle actions. It is used internally for # the Game_Battler class. #============================================================================== class Game_ActionResult attr_accessor :interrupted #-------------------------------------------------------------------------- # * Alias :Clear Hit Flags #-------------------------------------------------------------------------- alias clear_hit_flags_dnd clear_hit_flags def clear_hit_flags @interrupted = false clear_hit_flags_dnd end #-------------------------------------------------------------------------- # * overwrite :hit? #-------------------------------------------------------------------------- def hit? @used && !@missed && !@evaded && !@interrupted end end #============================================================================== # ** Core Damage Processing # ----------------------------------------------------------------------------- # I altered the way how damage calculation to provide more flexibility. Any # scripts that also overwrite make_damage_value will highly incompatible. # # However, I don't have any script implements this module right now. So you # may disable it # ----------------------------------------------------------------------------- if $imported[:Theo_CoreDamage] # Activation flag #============================================================================== class Game_Battler < Game_BattlerBase # --------------------------------------------------------------------------- # *) Overwrite make damage value # tag: damage # --------------------------------------------------------------------------- def make_damage_value(user, item) value = base_damage(user, item) globalize_damage_type(item) value = apply_element_rate(user, item, value) value = process_damage_rate(user, item, value) value = apply_other_effect(user,item,value) value = apply_damage_modifiers(user, item, value) @dmg_popup = true user.dmg_popup = true @result.make_damage(value.to_i, item) apply_after_effect(user,item,value) end # --------------------------------------------------------------------------- # *) Make base damage. Evaling damage formula # --------------------------------------------------------------------------- def base_damage(user, item) value = item.damage.eval(user, self, $game_variables) value end # --------------------------------------------------------------------------- # *) Apply element rate # --------------------------------------------------------------------------- def apply_element_rate(user, item, value) value *= item_element_rate(user, item) value end # --------------------------------------------------------------------------- # *) Apply damage rate. Such as physical, magical, recovery # --------------------------------------------------------------------------- def process_damage_rate(user, item, value) value *= pdr if item.physical? value *= mdr if item.magical? value *= rec if item.damage.recover? value end # --------------------------------------------------------------------------- # *) Apply damage modifier. Such as guard, critical, variance # --------------------------------------------------------------------------- def apply_damage_modifiers(user, item, value) value = apply_critical(value, user,item) if @result.critical value = apply_variance(value, item.damage.variance) value = apply_guard(value) value end # --------------------------------------------------------------------------- # *) Applying critical # --------------------------------------------------------------------------- def apply_critical(damage, user,item) multiplier = 1.5 ori_mul = 1.5 #--------------------------------------------------------------------------- # Coup de grace #--------------------------------------------------------------------------- if self.skill_learned?(637) multiplier = 4 if item.is_normal_attack end #--------------------------------------------------------------------------- # Exploit Weakness #--------------------------------------------------------------------------- if user.skill_learned?(648) if multiplier == ori_mul multiplier *+ 1.03 else multiplier += 0.3 end end #---------------------------- return damage * multiplier end # --------------------------------------------------------------------------- # *) Apply other effect # --------------------------------------------------------------------------- def apply_other_effect(user, item, value) multiplier = 1 #--------------------------------------------------------------------------- # Lacerate #--------------------------------------------------------------------------- if user.skill_learned?(649) && !self.state?(226) && value > 0 && self.opposite?(user) self.bleed if user.difficulty_class('str') > self.saving_throw('str') end #--------------------------------------------------------------------------- # Weak Points #--------------------------------------------------------------------------- multiplier += 0.3 if user.state?(262) #--------------------------------------------------------------------------- # Powerful Swings #--------------------------------------------------------------------------- if user.state?(249) if multiplier == 1 multiplier += 0.2 else multiplier *= 1.04 end end #--------------------------------------------------------------------------- # Spell Might #--------------------------------------------------------------------------- if user.state?(268) && item.magical? if multiplier == 1 multiplier = 1.2 multiplier += user.real_int * 0.01 unless user.real_int.nil? else multiplier *= 1.04 end end #--------------------------- value *= 0.4 if $enemy_chain_skill == true return value * multiplier end # --------------------------------------------------------------------------- # *) Apply after effect # --------------------------------------------------------------------------- def apply_after_effect(user, item, value) #--------------------------------------------------------------------------- # Feast of Fallen #--------------------------------------------------------------------------- if user.skill_learned?(650) && value > 0 user.hp += [value * 0.005 ,1].max.to_i user.mp += [value * 0.002 ,1].max.to_i end end # --------------------------------------------------------------------------- # *) Globalize damage type # --------------------------------------------------------------------------- def globalize_damage_type(item) if item.magical? $current_damage_type = 2 elsif item.physical? $current_damage_type = 1 else $current_damage_type = 0 end end end end #============================================================================= # ** Core Damage Result ~ #----------------------------------------------------------------------------- # I altered how action result is being handled. It's used within my sideview # battle system. #----------------------------------------------------------------------------- if $imported[:Theo_CoreResult] # Activation flag #============================================================================= class Game_Battler < Game_BattlerBase # --------------------------------------------------------------------------- # *) Apply item # --------------------------------------------------------------------------- def item_apply(user, item) make_base_result(user, item) apply_hit(user, item) if @result.hit? end # --------------------------------------------------------------------------- # *) Make base result # --------------------------------------------------------------------------- def make_base_result(user, item) @result.clear @result.used = item_test(user, item) @result.missed = determind_missed(user,item) @result.evaded = determind_evaded(user,item) @result.interrupted = determind_interrupted(user,item) end # --------------------------------------------------------------------------- # *) Determind missed # --------------------------------------------------------------------------- def determind_missed(user,item) return false unless @result.used return true if @base_attack_roll == 1 rand >= item_hit(user, item) end # --------------------------------------------------------------------------- # *) Determind evaded # --------------------------------------------------------------------------- def determind_evaded(user,item) return false if @result.missed return false unless opposite?(user) dex_bonus = self.difficulty_class('dex',-10,false) * 0.01 rand < ( item_eva(user, item) + dex_bonus) end # --------------------------------------------------------------------------- # *) Determind interrupted # --------------------------------------------------------------------------- def determind_interrupted(user,item) return true if user.state?(PONY::COMBAT_STOP_FLAG) result = false result ||= check_skill_interruption(user, item) result ||= check_state_interruption(user, item) return result end # --------------------------------------------------------------------------- # *) Apply hit # --------------------------------------------------------------------------- def apply_hit(user, item) unless item.damage.none? determine_critical(user, item) make_damage_value(user, item) execute_damage(user) end apply_item_effects(user, item) end # --------------------------------------------------------------------------- # *) Determind if critical hit # --------------------------------------------------------------------------- def determine_critical(user, item) return true if @base_attack_roll == 20 @result.critical = (rand < item_cri(user, item)) end # --------------------------------------------------------------------------- # *) Apply item effects # --------------------------------------------------------------------------- def apply_item_effects(user, item) for effect in item.effects return if @result.blocked return if self.state?(272) if effect.code == 21 if self.anti_magic? && $current_damage_type == 2 && $data_states[effect.data_id].is_magic? next end end item_effect_apply(user, item, effect) end item_user_effect(user, item) end end # class Game_Battler end # if $imported[:Theo_CoreResult]
class Comment < ActiveRecord::Base belongs_to :post belongs_to :account validates_presence_of :comment, :length=>{:maximum=>140 } sifter :or_comment do |string| comment.matches("%#{string}%") end before_save :make_slug def to_param slug end def slug if comment.length <= 24 slug = prep_slug(comment) else slug = prep_slug(comment.slice(0,24)) end end def make_slug self.slug = slug end def prep_slug(str) str.gsub(" ", "-") end end