text
stringlengths
10
2.61M
class Api::V1::IngredientsController < Api::V1::BaseController skip_before_action :verify_authenticity_token def create @ingredient = Ingredient.new(ingredient_params) unless @ingredient.save render_error end end def update @ingredient = Ingredient.find(params[:id]) unless @ingredient.update(ingredient_params) render_error end end def destroy @ingredient = Ingredient.find(params[:id]) @ingredient.destroy head :no_content end private def ingredient_params params.require(:ingredient).permit(:name, :product_id) end def render_error render json: { errors: @ingredient.errors.full_messages }, status: :unprocessable_entity end end
json.array!(@arts_types) do |arts_type| json.extract! arts_type, :id json.extract! arts_type, :name json.extract! arts_type, :description json.url arts_type_url(arts_type, format: :json) end
class Camp < ActiveRecord::Base has_many :students validates :branch, :street, :city, presence: true validates :state, length: { is: 2 } end
class Post < ApplicationRecord belongs_to :member validates :body, length: { in: (7..100) } end
class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :email, limit: 100 t.string :roles, array: true t.string :password_digest t.string :first_name, limit: 50 t.string :last_name, limit: 50 t.date :birthday t.string :phone, limit: 15 t.timestamps null: false end end end
# Factorial # I worked on this challenge [with: Karen Ball]. # Your Solution Below #def factorial(number) # Your code goes here # if number == 0 # return 1 # end # n_array = Array.new(number) # n_array.each do |x| # n_array[x] = number # number = number - 1 # end # out = 1 # n_array.each do |y| # out = y*out # end # return out #end def factorial(number) f = 1 while number > 0 f = f * number number = number - 1 end return f end
require 'rails_helper' RSpec.feature "Listing members" do before do @john=User.create(first_name:"John",last_name:"Doe",email:"john@gmail.com",password:"password") @sarah=User.create(first_name:"Sarah",last_name:"Joseph",email:"sarah@gmail.com",password:"password") end scenario "only registered users" do visit '/' expect(page).to have_content("List of Members") expect(page).to have_content(@john.full_name) expect(page).to have_content(@sarah.full_name) end end
class StocksController < ApplicationController before_action :set_stock, only: [:show, :edit, :update, :destroy] protect_from_forgery except: [:create, :update] # GET /stocks # GET /stocks.json def index @stocks = Stock.all end # GET /stocks/1 # GET /stocks/1.json def show end # GET /stocks/new def new @stock = Stock.new end # GET /stocks/1/edit def edit end # POST /stocks # POST /stocks.json def create @stock = Stock.new(stock_params) respond_to do |format| if @stock.save format.html { redirect_to @stock, notice: 'Stock was successfully created.' } format.json { render action: 'show', status: :created, location: @stock } else format.html { render action: 'new' } format.json { render json: @stock.errors, status: :unprocessable_entity } end end end # PATCH/PUT /stocks/1 # PATCH/PUT /stocks/1.json def update respond_to do |format| if @stock.update(stock_params) format.html { redirect_to @stock, notice: 'Stock was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @stock.errors, status: :unprocessable_entity } end end end # DELETE /stocks/1 # DELETE /stocks/1.json def destroy @stock.destroy respond_to do |format| format.html { redirect_to stocks_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_stock @stock = Stock.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def stock_params params.require(:stock).permit( :id, :product_id, :store_id, :g1, :g1h, :g2, :g2h, :g3, :g3h, :g4, :g4h, :g5, :g5h, :g6, :g6h, :g7, :g7h, :g8, :g8h, :g9, :g9h, :g10, :g10h, :g11, :g11h, :g12, :g12h, :g13, :g13h, :g14, :g14h, :g15, :g16, :g17, :g18, :g19 ) end end
class ApplicationController < ActionController::Base protect_from_forgery private def current_cart Cart.find(session[:cart_id]) # выдал ли браузер сессию rescue ActiveRecord::RecordNotFound cart = Cart.create # если нет создаем новую корзину session[:cart_id] = cart.id # создаем сессию == id таблицы cart # возврящаем корзину end end
class AccessRequest < Hashable belongs_to :authorization_request attr_accessor :code attr_accessible :grant_type, :redirect_uri, :scope, :state, :code def validate_request if grant_type.nil? or code.nil? return error_response "invalid_request" end unless grant_type == "authorization_code" return error_response "unsupported_grant_type" end auth_request = AuthorizationRequest.find_by_code(code) if auth_request.nil? or auth_request.invalid? return error_response "invalid_client" else unless auth_request.redirect_uri == redirect_uri and auth_request.state == state return error_response "invalid_grant" end unless auth_request.scope == scope return error_response "invalid_scope" end # Now Starts the successful request end end def error_response error_message hash = Hash.new hash[:error] = error_message hash[:state] = state unless state.nil? return hash end def successful_response hash = Hash.new hash[:access_token] = generate_access_token hash[:refresh_token] = generate_refresh_token hash[:state] = state unless state.nil? return hash end def generate_access_token self.access_token = "abc123" self.expire_in = 3600 end def generate_refresh_token self.refresh_token = "abc123" end end
class Xero::DonationsService < Xero::BaseService def load bank_transaction_scope.each do |bank_transaction| bank_transaction.line_items.each do |line_item| next unless designation_account_codes.keys.include?(line_item.account_code) attributes = donation_attributes(line_item, bank_transaction) record = Donation.find_or_initialize_by(id: line_item.line_item_id) record.attributes = attributes record.save! end end end private def bank_transaction_scope(page = 1) Enumerator.new do |enumerable| loop do data = call_bank_transaction_api(page) data.each { |element| enumerable.yield element } break if data.empty? page += 1 end end end def call_bank_transaction_api(page) client.BankTransaction.all( modified_since: @modified_since, where: 'Type=="RECEIVE" and Status=="AUTHORISED"', page: page ) rescue Xeroizer::OAuth::RateLimitExceeded sleep 60 retry end def donation_attributes(line_item, bank_transaction, attributes = {}) attributes[:id] = line_item.line_item_id attributes[:designation_account_id] = designation_account_codes[line_item.account_code] attributes[:created_at] = bank_transaction.date attributes[:donor_account_id] = bank_transaction.contact.id attributes[:currency] = bank_transaction.currency_code attributes[:amount] = line_item.line_amount attributes rescue Xeroizer::OAuth::RateLimitExceeded sleep 60 retry end def designation_account_codes return @designation_account_codes if @designation_account_codes @designation_account_codes = {} DesignationAccount.where(active: true).each do |designation_account| @designation_account_codes[designation_account.remote_id] = designation_account.id end @designation_account_codes end end
class Subscription < ActiveRecord::Base include ModelStatus include Scrollable attr_accessible :current, :documents_attributes, :end_date, :cost, :owner_id, :owner_type, :paid, :start_date, :status belongs_to :owner, polymorphic: true, inverse_of: :subscriptions has_many :documents, as: :owner, inverse_of: :owner accepts_nested_attributes_for :documents validate :start_date, presence: true before_save :set_end_date after_save :set_status_before_save #after_save :move_subscription_files before_update :set_end_date, :set_status_before_save default_scope order: 'start_date DESC' scope :current, where( current: true).limit(1) def designations (documents.any? ? documents.map{ |d| d.designation.to_sym unless d.id.blank? }.compact : []) #(documents.any? ? documents.map{ |d| d.designation.to_sym } : []) #@_designations ||= (documents.any? ? documents.map{ |d| d.designation.to_sym } : []) end def move_subscription_files if documents.any? documents.each do |doc| debug "asset path" debug "#{self.owner.asset_path}" doc.rename_file! self.owner.asset_path unless doc.renamed? end end end private # Ugly code :( def initialize_status_before_save debug "initialize_status_before_save" if pending_payment? && paid? paid = true status = :payment_received else paid = false status = if documents.any? debug designations # what if invoice but no MBF/SA ? if designations.include? :invoice # Invoice? :pending_payment elsif (designations & [ :membership_form, :service_agreement ]).size == 2 #SA & MBF? :pending_invoice elsif designations.include? :membership_form # MBF ? :pending_sa else # SA ? :pending_mbf end else :pending_documents end end [ paid, status ] end def set_status_before_save debug "set_status_before_save" unless payment_received? paid, status = false, :new if documents.size == 3 && paid? paid, status = true, :payment_received else paid, status = initialize_status_before_save end self.status = status self.paid = paid end true end def set_end_date debug "set_end_date" self.end_date = if paid? or expired? Date.current.end_of_year elsif self.created_at.nil? Date.current + 30.days else self.created_at.to_date + 30.days end true end def validate_start_date debug "validate_start_date" date_down = Date.current - 3.months date_up = Date.current + 3.months if ( date_down .. date_up ).cover? self.start_date debug "TRUE!!!!!" true else debug "FALSE !!!!!" self.errors.add(:start_date, "Invalid start date. Please choose a date between #{date_down.strftime('%B %d, %Y')} and #{date_up.strftime('%B %d, %Y')}") false end true end end
require "test_helper" class CageStatusesControllerTest < ActionDispatch::IntegrationTest setup do @cage_status = cage_statuses(:one) end test "should get index" do get cage_statuses_url assert_response :success end test "should get new" do get new_cage_status_url assert_response :success end test "should create cage_status" do assert_difference('CageStatus.count') do post cage_statuses_url, params: { cage_status: { name: @cage_status.name } } end assert_redirected_to cage_status_url(CageStatus.last) end test "should show cage_status" do get cage_status_url(@cage_status) assert_response :success end test "should get edit" do get edit_cage_status_url(@cage_status) assert_response :success end test "should update cage_status" do patch cage_status_url(@cage_status), params: { cage_status: { name: @cage_status.name } } assert_redirected_to cage_status_url(@cage_status) end test "should destroy cage_status" do assert_difference('CageStatus.count', -1) do delete cage_status_url(@cage_status) end assert_redirected_to cage_statuses_url end end
# -*- coding: UTF-8 -*- # Persian module module Persian # Persian Text class # Digest Persian texts class Text # Replace Arabic characters with Persian characters. def self.character(text) AR_FA_CHAR.each { |k, v| text.gsub!(k, v) } text end # Remove extra spaces in text def self.remove_extra_spaces(text) text = text.split.join(' ') text = text.split('‌').join('‌') text end # Remove Arabic harecats from text def self.remove_harekats(text) HAREKATS.each { |v| text = text.gsub(v, '') } text end # Remove All barckets def self.remove_brackets(text) BRACKETS.each { |v| text = text.gsub(v, '') } text end # Remove Persian signs def self.remove_signs(text, with = '') return '' if text.nil? SIGNS.each { |v| text = text.gsub(v, with) } text end def self.replace_zwnj_with_space(text) text = text.gsub(/(‌)/, ' ') text end # Replace general brackets with one type brackets # Default: 0xAB & 0xBB def self.general_brackets(text, left = '«', right = '»') text = text.gsub(/"(.*?)"/, left + '\1' + right) text = text.gsub(/\[(.*?)\]/, left + '\1' + right) text = text.gsub(/\{(.*?)\}/, left + '\1' + right) text = text.gsub(/\((.*?)\)/, left + '\1' + right) text end # Add '‌ی' after names that end with ه, ا, و def self.fix_y_after_vowel(text) text += '‌ی' if END_VOWEL.include? text[-1] text end # Replace Space with Zero-width none-joiner after می and نمی def self.replace_zwnj_mi(text) mi = 'می' nmi = 'نمی' text.gsub!(/(^|\s)(#{mi}|#{nmi})\s(\S+)/, '\1\2‌\3') text end # Resplace ست with \sاست if lastest character before \s is ا def self.ast(text) a = 'ا' ast = 'است' st = 'ست' text.gsub!(/(#{a})\s(#{ast})/, '\1' + st) text end # Remove keshide from text def self.keshide(text) text.gsub!(/ـ+/, '') text end # Use ی instead of ئ if next char is ی # Example پائیز => پاییز def self.replace_e_y(text) e = 'ئ' y = 'ی' text.gsub!(/#{e}(#{y})/, '\1\1') text end def self.three_dots(text) text.gsub!(/\.{3,}/, '…') text end def self.suffix(text) tar = 'تر' ee = 'ی' n = 'ن' ha = 'ها' ye = 'ی' text.gsub!(/\s+(#{tar}(#{ee}(#{n})?)?)|(#{ha}(#{ye})?)\s+/, '‌\1') text end def self.remove_extra_question_mark(text) mark = '؟' text.gsub!(/(#{mark}){2,}/, '\1') text end def self.add_zwnj(text, point) text = text.scan(/^.{#{point}}|.+/).join('‌') text end def self.remove_question_exclamation(text) question = '؟' exclamation = '!' text.gsub!(/(#{question})+(#{exclamation})+/, '\1\2') text end def self.remove_stopwords(text) stopwords = ['و', 'در', 'به', 'این', 'با', 'از', 'که', 'است', 'را'] words = text.scan(/\S+/) keywords = words.select { |word| !stopwords.include?(word) } keywords.join(' ') end def self.remove_space_noghtevirgool(text) noghtevirgool = '؛' text.gsub!(/\s+(#{noghtevirgool})/, '\1') text end def self.remove_signs_after_noghtevirgool(text) signs = '[\.،؛:!؟\-…]' noghtevirgool = '؛' text.gsub!(/(#{noghtevirgool})[#{signs}]+/, '\1') text end def self.space_after_noghtevirgool(text) noghtevirgool = '؛' text.gsub!(/(#{noghtevirgool})(\S)/, '\1 \2') text end def self.remove_noghtevirgool_para_end(text) noghtevirgool = '؛' text.gsub!(/#{noghtevirgool}(\n|$)/, '.\1') text end def self.remove_noghtevirgool_baz_start(text) noghtevirgool = '؛' regex = /([\(\[«])[ ‌]*[#{noghtevirgool}]/ text.gsub!(regex, '\1') text end def self.remove_space_before_virgool(text) virgool = '،' text.gsub!(/\s+(#{virgool})/, '\1') text end def self.remove_signs_after_virgool(text) pattern = /(،)([ ‌]+)?([،؛:!؟\-][\.،؛:!؟\-]*|\.(?!\.))/ text.gsub!(pattern, '\1\2') text end def self.space_after_virgool(text) virgool = '،' text.gsub!(/(#{virgool})(\S)/, '\1 \2') text end def self.rm_char(text, char) text.gsub!(/(#{char})/, '') text end def self.rm_virgool_in_end(text) text.gsub!(/(،)([ ‌\n]+)?$/, '.\2') text end def self.space_after_dot(text) text.gsub!(/(\.)(\S)/, '\1 \2') text end def self.squeeze(text) text.squeeze end # Remove specific character from end of text # EXample: remove_postfix('پسره','ه') def self.remove_postfix(text, postfix) text.chomp!(postfix) text end end end
class User < ApplicationRecord has_secure_password VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i has_many :research_users has_many :researches, through: :research_users validates :username, presence: { message: "Usuario no puede ir vacio" }, uniqueness: { case_sensitive: false, message: "Ya hay otro usuario con el mismo username" } validates :email, presence: { message: "Email no puede ir vacio"}, uniqueness: { case_sensitive: false, message: "Ya hay otro usuario con el mismo email" }, format: { with: VALID_EMAIL_REGEX, message: "El email introducido no es valido" } validates :firstname, presence: { message: "Nombre no puede ir vacio" } validates :lastname, presence: { message: "Apellidos no puede ir vacio" } validates :password_digest, presence: { message: "Contraseña no puede ir vacia" } def say_hello return "Hola #{firstname}".strip if (firstname) "Hola Desconocido" end def full_name return "#{firstname}".strip + " " + "#{lastname}".strip end def exclude_system_admin(users) users.reject { |user| user.username == "system.admin" && self.id != user.id } end def self.all_users users = self.all.order(firstname: :asc) users.reject { |user| user.username == "system.admin" } end def admin? self.is_admin end def owner?(research) research.owner.id === self.id end def get_privileges(research) role = get_role(research) p = { :can_create => self.can_create(role), :can_read => self.can_read(role), :can_update => self.can_update(role), :can_audit => self.can_audit(role), :can_delete => self.can_delete(role) } return p end def can_create(role) return role.nil? ? false : role.can_create end def can_read(role) return role.nil? ? false : role.can_read end def can_update(role) return role.nil? ? false : role.can_update end def can_delete(role) return role.nil? ? false : role.can_delete end def can_audit(role) return role.nil? ? false : role.can_audit end def get_role(research) ru = self.research_users.where(research_id: research.id).first if !ru.blank? return ru.role end return nil end end
# -*- ruby -*- require 'rubygems' require 'rake/testtask' require 'rake/gempackagetask' $:.push 'lib' require 'talktosolr' PKG_NAME = 'talktosolr' PKG_VERSION = TalkToSolr::VERSION spec = Gem::Specification.new do |s| s.name = PKG_NAME s.version = PKG_VERSION s.summary = 'Talk to Solr search' s.files = FileList['lib/**/*.rb'] s.test_files = FileList['test/*.rb'] s.has_rdoc = true s.rdoc_options << '--title' << 'TalkToSolr' << '--charset' << 'utf-8' s.author = 'Peter Hickman' s.email = 'peterhi@ntlworld.com' # s.homepage = 'http://thumbnailer.rubyforge.org' # s.rubyforge_project = 'thumbnailer' end Rake::GemPackageTask.new(spec) do |pkg| pkg.need_tar = true end desc "Run all the tests" Rake::TestTask.new("test") do |t| t.pattern = 'tests/*.rb' t.verbose = false t.warning = true end
directory node['chef_server_populator']['backup']['dir'] do recursive true owner 'opscode-pgsql' mode '0755' end # Upload to Remote Storage # Include fog case node['platform_family'] when 'debian' packages = %w(gcc libxml2 libxml2-dev libxslt-dev) when 'rhel' packages = %w(gcc libxml2 libxml2-devel libxslt libxslt-devel patch) end packages.each do |fog_dep| package fog_dep end node['chef_server_populator']['backup_gems'].each_pair do |gem_name, gem_version| gem_package gem_name do unless gem_version.nil? version gem_version end retries 2 end end directory node['chef_server_populator']['configuration_directory'] do recursive true owner 'root' mode '700' end file File.join(node['chef_server_populator']['configuration_directory'], 'backup.json') do content Chef::JSONCompat.to_json_pretty( node['chef_server_populator']['backup'].merge( cookbook_version: node.run_context.cookbook_collection['chef-server-populator'].version ) ) owner 'root' mode '600' end template '/usr/local/bin/chef-server-backup' do source 'chef-server-backup.rb.erb' mode '0700' retries 3 end cron 'Chef Server Backups' do command '/usr/local/bin/chef-server-backup' node['chef_server_populator']['backup']['schedule'].each do |k, v| send(k, v) end path '/opt/chef/embedded/bin/:/usr/bin:/usr/local/bin:/bin' end
class Game ACTIONS = %i[place report move right left] def initialize @move_robot ||= RobotMoviments.new end def place point="" move_robot.to(point) end def move _ move_robot.forward end def right _ move_robot.to.right end def left _ move_robot.to.left end def report _ move_robot.report end def respond_to? meth return true if game_action? meth super end private attr_reader :move_robot def game_action? meth ACTIONS.include? meth.to_s.downcase.to_sym end def method_missing(meth, *args, &block) if game_action? meth, *args plublic_send meth.to_s.downcase.to_sym else super end end end
class AddReferencesToMission < ActiveRecord::Migration[6.0] def change add_reference :missions, :user, index: true, null: false end end
module Cli class Juniper def initialize(device) @device = device end def platform raw = `jlogin -c "show version" #{@device.fqdn}` raw =~ /> show version\s*$.*Model:\s*(.*)$.*\[(.*)\]\s*$/m {'machine' => $1.try(&:strip), 'os-name' => 'JUNOS', 'os-version' => $2.try(:strip)} end end end
class SampleSerializer < ActiveModel::Serializer attributes :id, :genius_id, :song_title, :primary_artist, :song_id belongs_to :song end
# frozen_string_literal: true module Sentry class Breadcrumb DATA_SERIALIZATION_ERROR_MESSAGE = "[data were removed due to serialization issues]" # @return [String, nil] attr_accessor :category # @return [Hash, nil] attr_accessor :data # @return [String, nil] attr_accessor :level # @return [Time, Integer, nil] attr_accessor :timestamp # @return [String, nil] attr_accessor :type # @return [String, nil] attr_reader :message # @param category [String, nil] # @param data [Hash, nil] # @param message [String, nil] # @param timestamp [Time, Integer, nil] # @param level [String, nil] # @param type [String, nil] def initialize(category: nil, data: nil, message: nil, timestamp: nil, level: nil, type: nil) @category = category @data = data || {} @level = level @timestamp = timestamp || Sentry.utc_now.to_i @type = type self.message = message end # @return [Hash] def to_hash { category: @category, data: serialized_data, level: @level, message: @message, timestamp: @timestamp, type: @type } end # @param message [String] # @return [void] def message=(message) @message = (message || "").byteslice(0..Event::MAX_MESSAGE_SIZE_IN_BYTES) end private def serialized_data begin ::JSON.parse(::JSON.generate(@data)) rescue Exception => e Sentry.logger.debug(LOGGER_PROGNAME) do <<~MSG can't serialize breadcrumb data because of error: #{e} data: #{@data} MSG end DATA_SERIALIZATION_ERROR_MESSAGE end end end end
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe BoardPost do before(:each) do @valid_attributes = { } end it "should create a new instance given valid attributes" do BoardPost.create!(@valid_attributes) end it "should acquire posts from the internet (using Mechanize)" do id = 5146587 res = BoardPost.acquire_post(id) res.id.should == id res.title.should == "кстати, наш военком выписывает предупреждение, если ты сам пришел, а не милиция доставила :)" res.body.should == "кстати, в принципе, если стоишь на учете, то с чего тебе без повестки шляться? только если сменил место жительства там или работы. а для первичной постановки при этом, как ни странно, являться тоже надо по повестке. вот такая интересная коллизия: с одной стороны, ты обязан стоять на учете, а с другой -- вставать на учет надо по повестке <IMG BORDER=0 SRC=\"pic/smile.gif\" ALT=\":)\">" end it "should acquire posts from the internet with no body (-)" do id = 5146593 res = BoardPost.acquire_post(id) res.id.should == id res.title.should == "+" res.body.should be_nil end it "should acquire post #5146594" do id = 5146594 res = BoardPost.acquire_post(id) res.id.should == id res.title.should == "Я в Питер за 5 часов не доеду." res.body.should be_nil end it "should acquire deleted post as entries with null body field" do [5146693, 5146700, 5146703].each do |id| res = BoardPost.acquire_post(id) res.id.should == id res.body.should be_nil end end it "should have post method using scrubyt" it "should parse post # 5246165, okay?" do post = BoardPost.acquire_post(5246165) post.id.should == 5246165 post.title.should == "8ka, народ , вы в курсе когда нам включат холодую воду?" end end
# encoding: UTF-8 class Department include Mongoid::Document include Mongoid::Timestamps::Short field :n, as: :name, type: String field :fn, as: :full_name, type: String, default: -> { name } field :_id, type: String, default: -> { name } validates :name, presence: true, length: { minimum: 3 }, uniqueness: true embeds_many :homepage_docs, class_name: 'DepartmentDocument' has_many :courses, autosave: true has_and_belongs_to_many :teachers, autosave: true do def current where(current: true) end end def to_s self.full_name end end
#!/usr/bin/ruby # -*- coding: utf-8 -*- module Apex module Converter # # ApexコードをJavaDocが解釈できるJavaコードに変換します。 # # ApexとJavaのコード仕様の違いをなるべく吸収し、JavaDocで解釈可能なスケルトン # コードとして出力します。主な相違点は下記のとおりです。 # # - 文字列リテラル # Javaではシングルクオーテーションで囲まれた文字列は1つの文字のみをあらわし # ますがApexではシングルクオートで文字列を表現します。そのためApexコード中 # のすべての文字列リテラルはJavaの規則に沿うようにダブルクオーテーションに # 置換されます。 # # - virtual with/without sharing 修飾 # - override 修飾 # def to_java result = "" in_comment = false @code.each_line do |line| #----------------------------------------------------------------------- # Javaで解釈できないコードを削除する #----------------------------------------------------------------------- line.chomp! line.gsub!(/\"/,"\\\"") line.gsub!(/\'/,"\"") line.sub!(/global /,'public ') line.sub!(/virtual /,'') line.sub!(/with /,'') line.sub!(/without /,'') line.sub!(/sharing /,'') line.sub!(/override /,'') line.gsub!(/ string /, ' String ') line.gsub!(/ integer /, ' Integer ') line.gsub!(/Class/, 'class') line.gsub!(/MAP/, 'Map') if line =~ /\/\// line.sub!(/\/\//,'/*') line += "*/" end #----------------------------------------------------------------------- # コメントモードの場合、改行を付加して出力行内にコメント終了トークンが # ある場合はコメントモードを終了する #----------------------------------------------------------------------- if in_comment in_comment = false if line =~ R_COMMENT_END result += line + "\n" else #----------------------------------------------------------------------- # コメントモードでないときに、行内にコメント開始がある場合コメントモー # ドを開始し改行を付加して出力 #----------------------------------------------------------------------- if line =~ R_COMMENT_START in_comment = true unless line =~ R_COMMENT_END result += line + "\n" else #----------------------------------------------------------------------- # コメントモードでなく行内にコメント開始がない場合、クラス、メソッド、 # フィールドのいずれかであるか判定する #----------------------------------------------------------------------- ## クラス定義の場合、改行を付加して出力 #----------------------------------------------------------------------- if line =~ R_DEF_CLASS if line =~ /\{/ line = line + "\n" else line = line + "{\n" end result += line #----------------------------------------------------------------------- ## コンストラクタ定義の場合、中括弧を閉じて出力 #----------------------------------------------------------------------- elsif line =~ R_DEF_CONSTRACTOR if line =~ /\}/ line = line + "\n" else line = line + "}\n" end result += line #----------------------------------------------------------------------- ## メソッド定義の場合、抽象メソッドは改行を付加して出力する ## メソッドの型がvoidの場合は中括弧を閉じそれ以外の場合はnullを返すコー ## ドを付加して出力 #----------------------------------------------------------------------- elsif line =~ R_DEF_METHOD unless $2 =~ /abstract/ if $3 == "void" if line =~ /\}/ line = line + "\n" else line = line + "}\n" end else if line =~ /\}/ line = line + "\n" else line = line + "return null;}\n" end end end result += line #----------------------------------------------------------------------- ## フィールド定義の場合、改行を付加して出力 #----------------------------------------------------------------------- elsif line =~ R_DEF_FIELD result += line + "\n" end end end end result + "\n}\n" end end end
# -*- mode: ruby -*- # vi: set ft=ruby : version = "v1.4.0" Vagrant.configure("2") do |config| config.vm.box = "ubuntu/bionic64" config.vm.provision "shell", inline: <<-SHELL apt update apt install -y curl unzip SHELL config.vm.provision "shell", inline: <<-SHELL curl -LO "https://github.com/grafana/loki/releases/download/#{version}/loki-linux-amd64.zip" unzip "loki-linux-amd64.zip" chmod +x "loki-linux-amd64" mv "loki-linux-amd64" "/usr/local/bin/loki" rm -rf "loki-linux-amd64.zip" SHELL config.vm.provision "shell", inline: <<-SHELL curl -LO "https://github.com/grafana/loki/releases/download/#{version}/logcli-linux-arm64.zip" unzip "logcli-linux-arm64.zip" chmod +x "logcli-linux-arm64" mv "logcli-linux-arm64" "/usr/local/bin/logcli" rm -rf "logcli-linux-arm64.zip" SHELL config.vm.provision "shell", inline: <<-SHELL curl -LO "https://github.com/grafana/loki/releases/download/#{version}/promtail-linux-amd64.zip" unzip "promtail-linux-amd64.zip" chmod +x "promtail-linux-amd64" mv "promtail-linux-amd64" "/usr/local/bin/promtail" rm -rf "promtail-linux-amd64.zip" SHELL end
class Store include Mongoid::Document field :name, type: String belongs_to :user end
ActiveRecord::Base.logger = Logger.new(STDOUT) class ExtractUsersFromPhotos < ActiveRecord::Migration def self.up execute <<ENDOFSQL delete from users; DROP TABLE IF EXISTS temp_users; DROP TABLE IF EXISTS temp_multiple_twitter; DROP TABLE IF EXISTS temp_multiple_facebook; DROP TABLE IF EXISTS temp_latest_facebook_data; CREATE TABLE temp_users ( "id" int4 DEFAULT NULL, "name" varchar(255) DEFAULT NULL, "created_at" timestamp(6) DEFAULT NULL, "updated_at" timestamp(6) DEFAULT NULL, "twitter_screen_name" varchar(255) DEFAULT NULL, "twitter_oauth_token" varchar(255) DEFAULT NULL, "twitter_oauth_secret" varchar(255) DEFAULT NULL, "twitter_avatar_url" varchar(255) DEFAULT NULL, "facebook_access_token" varchar(255) DEFAULT NULL, "facebook_user_id" varchar(255) DEFAULT NULL ) WITH (OIDS=FALSE); -- insert people with both mappings insert into temp_users (twitter_screen_name, facebook_user_id ) select distinct twitter_screen_name, facebook_user_id from photos where twitter_screen_name is not null and facebook_user_id is not null and twitter_screen_name<>'' and facebook_user_id<>''; -- insert people with twitter-only mapping insert into temp_users (twitter_screen_name ) select distinct twitter_screen_name from photos where (facebook_user_id is null or facebook_user_id = '') and twitter_screen_name not in (select twitter_screen_name from temp_users) and twitter_screen_name <> ''; -- insert people with facebook-only mapping insert into temp_users (facebook_user_id ) select distinct facebook_user_id from photos where (twitter_screen_name is null or twitter_screen_name = '') and facebook_user_id not in (select facebook_user_id from temp_users where facebook_user_id is not null); --identify duplicate twitter account and save them aside select facebook_user_id into temp_multiple_twitter from temp_users where facebook_user_id is not null group by facebook_user_id having count(*) > 1; --remove them all delete from temp_users where facebook_user_id in (select facebook_user_id from temp_multiple_twitter); --add back facebook_ids with latest twitter_screen_name insert into temp_users (twitter_screen_name, facebook_user_id ) select s.twitter_screen_name,s.facebook_user_id from temp_multiple_twitter t JOIN photos s ON s.facebook_user_id = t.facebook_user_id where s.twitter_screen_name is not null and twitter_screen_name <> '' and created_at = (select max(created_at) from photos pp where pp.facebook_user_id = t.facebook_user_id and pp.twitter_screen_name is not null and pp.twitter_screen_name <> ''); --check if all duplicates are gone select facebook_user_id from temp_users where facebook_user_id is not null group by facebook_user_id having count(*) > 1; --identify duplicate facebook accounts and save them aside select twitter_screen_name into temp_multiple_facebook from temp_users where twitter_screen_name is not null group by twitter_screen_name having count(*) > 1; --remove them all delete from temp_users where twitter_screen_name in (select twitter_screen_name from temp_multiple_facebook); --add back twitter_screen_name with latest facebook_user_id insert into temp_users (twitter_screen_name, facebook_user_id ) select s.twitter_screen_name,s.facebook_user_id from temp_multiple_facebook t JOIN photos s ON s.twitter_screen_name = t.twitter_screen_name where s.facebook_user_id is not null and facebook_user_id <> '' and created_at = (select max(created_at) from photos pp where pp.twitter_screen_name = t.twitter_screen_name and pp.facebook_user_id is not null and pp.facebook_user_id <> ''); --check if all duplicates are gone select twitter_screen_name from temp_users where twitter_screen_name is not null group by twitter_screen_name having count(*) > 1; -- get latest facebook user data drop index if exists idx1; drop index if exists idx2; create index idx1 on temp_users(facebook_user_id); create index idx2 on photos(facebook_user_id); select facebook_user_id, facebook_access_token into temp_latest_facebook_data from photos s where s.created_at = (select max(created_at) from photos pp where pp.facebook_user_id = s.facebook_user_id) ; create index idx3 on temp_latest_facebook_data(facebook_user_id); -- get latest twitter user data drop index if exists idx5; drop index if exists idx6; create index idx5 on temp_users(twitter_screen_name); create index idx6 on photos(twitter_screen_name); drop table if exists temp_latest_twitter_data; select twitter_screen_name,twitter_oauth_token,twitter_oauth_secret,twitter_avatar_url into temp_latest_twitter_data from photos s where s.created_at = (select max(created_at) from photos pp where pp.twitter_screen_name = s.twitter_screen_name) ; create index idx7 on temp_latest_twitter_data(twitter_screen_name); -- merge all results insert into users (facebook_user_id, twitter_screen_name, facebook_access_token,twitter_oauth_token,twitter_oauth_secret,twitter_avatar_url) select a.facebook_user_id, a.twitter_screen_name, b.facebook_access_token, c.twitter_oauth_token, c.twitter_oauth_secret, c.twitter_avatar_url from temp_users a left outer join temp_latest_facebook_data b on a.facebook_user_id=b.facebook_user_id left outer join temp_latest_twitter_data c on a.twitter_screen_name=c.twitter_screen_name; -- DROP temp table drop table temp_users; drop table temp_multiple_twitter; drop table temp_multiple_facebook; ENDOFSQL end def self.down end end
module IControl::LocalLB ## # The ProfilePersistence interface enables you to manipulate a local load balancer's # Persistence profile. class ProfilePersistence < IControl::Base set_id_name "profile_names" class ProfilePersistenceHashMethod < IControl::Base::Struct; end class PersistenceHashMethodSequence < IControl::Base::Sequence ; end class ProfilePersistenceHashMethodSequence < IControl::Base::Sequence ; end # Persistence hash methods used for persisting connections class PersistenceHashMethod < IControl::Base::Enumeration; end ## # Creates this Persistence profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::PersistenceMode] :modes The persistence modes for the specified profiles. def create(opts) opts = check_params(opts,[:modes]) super(opts) end ## # Deletes all Persistence profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def delete_all_profiles super end ## # Deletes this Persistence profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def delete_profile super end ## # Gets the states to indicate whether persistence entries added under this profile # are available across pools. # @rspec_example # @return [ProfileEnabledState] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def across_pool_state super end ## # Gets the states to indicate whether persistence entries added under this profile # are available across services. # @rspec_example # @return [ProfileEnabledState] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def across_service_state super end ## # Gets the states to indicate whether persistence entries added under this profile # are available across virtuals. # @rspec_example # @return [ProfileEnabledState] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def across_virtual_state super end ## # Gets the cookie expiration in seconds for this Persistence profile. Applicable when # peristence mode is PERSISTENCE_MODE_COOKIE. # @rspec_example # @return [ProfileULong] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def cookie_expiration super end ## # Gets the cookie hash lengths for this profile. Applicable when peristence mode is # PERSISTENCE_MODE_COOKIE, and cookie persistence method is COOKIE_PERSISTENCE_METHOD_HASH. # @rspec_example # @return [ProfileULong] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def cookie_hash_length super end ## # Gets the cookie hash offsets for this profile. Applicable when peristence mode is # PERSISTENCE_MODE_COOKIE, and cookie persistence method is COOKIE_PERSISTENCE_METHOD_HASH. # @rspec_example # @return [ProfileULong] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def cookie_hash_offset super end ## # Gets the cookie names for this Persistence profile. Applicable when peristence mode # is PERSISTENCE_MODE_COOKIE. # @rspec_example # @return [ProfileString] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def cookie_name super end ## # Gets the cookie persistence methods to be used when in cookie persistence mode. Applicable # when peristence mode is PERSISTENCE_MODE_COOKIE. # @rspec_example # @return [ProfileCookiePersistenceMethod] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def cookie_persistence_method super end ## # Gets the names of the default profile from which this profile will derive default # values for its attributes. # @rspec_example # @return [String] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def default_profile super end ## # Gets the pattern marking the end of the section of payload data whose hashed value # is used for the persistence value for a set of persistence profile. This only returns # useful values if the persistence mode is PERSISTENCE_MODE_HASH and the hash method # is PERSISTENCE_HASH_CARP. # @rspec_example # @return [ProfileString] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def ending_hash_pattern super end ## # Gets the length of payload data whose hashed value is used for the persistence value # for a set of persistence profile. This only returns useful values if the persistence # mode is PERSISTENCE_MODE_HASH and the hash method is PERSISTENCE_HASH_CARP. # @rspec_example # @return [ProfileULong] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def hash_length super end ## # Gets the hash method used to generate the persistence values for a set of persistence # profile. This only returns useful values if the persistence mode is PERSISTENCE_MODE_HASH. # @rspec_example # @return [ProfilePersistenceHashMethod] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def hash_method super end ## # Gets the enabled state whether to perform another hash operation after the current # hash operation completes for a set of persistence profile. This only returns useful # values if the persistence mode is PERSISTENCE_MODE_HASH and the hash method is PERSISTENCE_HASH_CARP. # @rspec_example # @return [ProfileEnabledState] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def hash_more_data_state super end ## # Gets the offset to the start of the payload data whose hashed value is used as the # persistence value for a set of persistence profile. This only returns useful values # if the persistence mode is PERSISTENCE_MODE_HASH and the hash method is PERSISTENCE_HASH_CARP. # @rspec_example # @return [ProfileULong] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def hash_offset super end ## # Gets a list of all Persistence profile. # @rspec_example # @return [String] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def list super end ## # Gets the states to indicate whether to map known proxies when the persistence mode # is source address affinity. # @rspec_example # @return [ProfileEnabledState] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def map_proxy_state super end ## # Gets the masks used in either simple or sticky persistence mode. # @rspec_example # @return [ProfileIPAddress] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def mask super end ## # Gets the maximum size of the buffer used to hold the section of the payload data # whose hashed value is used for the persistence value for a set of persistence values. # This only returns useful values if the persistence mode is PERSISTENCE_MODE_HASH # and the hash method is PERSISTENCE_HASH_CARP. # @rspec_example # @return [ProfileULong] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def maximum_hash_buffer_size super end ## # Gets the mirror states for this Persistence profile. # @rspec_example # @return [ProfileEnabledState] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def mirror_state super end ## # Gets the states to indicate whether MS terminal services have been configured without # a session directory for this Persistence profile. # @rspec_example # @return [ProfileEnabledState] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def msrdp_without_session_directory_state super end ## # Gets the persistence modes for this Persistence profile. # @rspec_example # @return [ProfilePersistenceMode] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def persistence_mode super end ## # Gets the UIE rules for this Persistence profile. Applicable when peristence mode # is PERSISTENCE_MODE_UIE. # @rspec_example # @return [ProfileString] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def rule super end ## # Gets the sip_info headers for this Persistence profile. Applicable when peristence # mode is PERSISTENCE_MODE_SIP. # @rspec_example # @return [ProfileString] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def sip_info super end ## # Gets the pattern marking the start of the section of payload data whose hashed value # is used for the persistence value for a set of persistence profile. This only returns # useful values if the persistence mode is PERSISTENCE_MODE_HASH and the hash method # is PERSISTENCE_HASH_CARP. # @rspec_example # @return [ProfileString] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def starting_hash_pattern super end ## # Gets the timeout for this Persistence profile. The number of seconds to timeout a # persistence entry. # @rspec_example # @return [ProfileULong] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def timeout super end ## # Gets the version information for this interface. # @rspec_example # @return [String] def version super end ## # Determines whether this profile are base/pre-configured profile, or user-defined # profile. # @rspec_example # @return [boolean] # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. def is_base_profile super end ## # Sets the states to indicate whether persistence entries added under this profile # are available across pools. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileEnabledState] :states The states for the specified Persistence profiles. def set_across_pool_state(opts) opts = check_params(opts,[:states]) super(opts) end ## # Sets the states to indicate whether persistence entries added under this profile # are available across services. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileEnabledState] :states The states for the specified Persistence profiles. def set_across_service_state(opts) opts = check_params(opts,[:states]) super(opts) end ## # Sets the states to indicate whether persistence entries added under this profile # are available across virtuals. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileEnabledState] :states The states for the specified Persistence profiles. def set_across_virtual_state(opts) opts = check_params(opts,[:states]) super(opts) end ## # Sets the cookie expiration in seconds for this Persistence profile. Applicable when # peristence mode is PERSISTENCE_MODE_COOKIE. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileULong] :expirations The cookie expirations for the specified Persistence profiles. def set_cookie_expiration(opts) opts = check_params(opts,[:expirations]) super(opts) end ## # Sets the cookie hash lengths for this profile. Applicable when peristence mode is # PERSISTENCE_MODE_COOKIE, and cookie persistence method is COOKIE_PERSISTENCE_METHOD_HASH. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileULong] :lengths The cookie hash lengths for the specified Persistence profiles. def set_cookie_hash_length(opts) opts = check_params(opts,[:lengths]) super(opts) end ## # Sets the cookie hash offsets for this profile. Applicable when peristence mode is # PERSISTENCE_MODE_COOKIE, and cookie persistence method is COOKIE_PERSISTENCE_METHOD_HASH. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileULong] :offsets The cookie hash offsets for the specified Persistence profiles. def set_cookie_hash_offset(opts) opts = check_params(opts,[:offsets]) super(opts) end ## # Sets the cookie names for this Persistence profile. Applicable when peristence mode # is PERSISTENCE_MODE_COOKIE. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileString] :cookie_names The cookie names for the specified Persistence profiles. def set_cookie_name(opts) opts = check_params(opts,[:cookie_names]) super(opts) end ## # Sets the cookie persistence methods to be used when in cookie persistence mode. Applicable # when peristence mode is PERSISTENCE_MODE_COOKIE. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileCookiePersistenceMethod] :methods The cookie persistence methods for the specified Persistence profiles. def set_cookie_persistence_method(opts) opts = check_params(opts,[:methods]) super(opts) end ## # Sets the names of the default profile from which this profile will derive default # values for its attributes. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [String] :defaults The default profiles from which the specified profiles will get default values. def set_default_profile(opts) opts = check_params(opts,[:defaults]) super(opts) end ## # Sets the pattern marking the end of the section of payload data whose hashed value # is used for the persistence value for a set of persistence profile. The hash payload # data is either delimited by this starting and ending string pattern or the offset # and length, not both. This is only applicable when the persistence mode is PERSISTENCE_MODE_HASH # and the hash method is PERSISTENCE_HASH_CARP. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileString] :patterns def set_ending_hash_pattern(opts) opts = check_params(opts,[:patterns]) super(opts) end ## # Sets the length of payload data whose hashed value is used for the persistence value # for a set of persistence profile. The start of the data is specified via set_hash_offset. # The hash payload data is either delimited by this offset and length or the starting # and ending string pattern, not both. This is only applicable when the persistence # mode is PERSISTENCE_MODE_HASH and the hash method is PERSISTENCE_HASH_CARP. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileULong] :lengths Hashed payload data length (bytes) for each specified persistence profile (default: 0). If zero, the hashed payload data is not specified by an offset and length. def set_hash_length(opts) opts = check_params(opts,[:lengths]) super(opts) end ## # Sets the hash method used to generate the persistence values for a set of persistence # profile. See PersistenceHashMethod for details. This is only applicable when the # persistence mode is PERSISTENCE_MODE_HASH. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfilePersistence::ProfilePersistenceHashMethod] :methods Persistence method for each specified profile (default: PERSISTENCE_HASH_DEFAULT) def set_hash_method(opts) opts = check_params(opts,[:methods]) super(opts) end ## # Sets the enabled state whether to perform another hash operation after the current # hash operation completes for a set of persistence profile. This is only applicable # when the persistence mode is PERSISTENCE_MODE_HASH and the hash method is PERSISTENCE_HASH_CARP. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileEnabledState] :states Enabled state for more hashing for each specified persistence profile (default: disabled) def set_hash_more_data_state(opts) opts = check_params(opts,[:states]) super(opts) end ## # Sets the offset to the start of the payload data whose hashed value is used as the # persistence value for a set of persistence profile. This is only applicable when # the persistence mode is PERSISTENCE_MODE_HASH and the hash method is PERSISTENCE_HASH_CARP. # The hashed payload data length is specified via set_hash_length. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileULong] :offsets Payload data offset (bytes) to the start of the hashed data for each specified persistence profile (default: 0) def set_hash_offset(opts) opts = check_params(opts,[:offsets]) super(opts) end ## # Sets the states to indicate whether to map known proxies when the persistence mode # is source address affinity. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileEnabledState] :states The states for the specified Persistence profiles. def set_map_proxy_state(opts) opts = check_params(opts,[:states]) super(opts) end ## # Sets the masks used in either simple or sticky persistence mode. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileIPAddress] :masks The masks for the specified Persistence profiles. def set_mask(opts) opts = check_params(opts,[:masks]) super(opts) end ## # Sets the maximum size of the buffer used to hold the section of the payload data # whose hashed value is used for the persistence value for a set of persistence values. # This is only applicable when the persistence mode is PERSISTENCE_MODE_HASH and the # hash method is PERSISTENCE_HASH_CARP. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileULong] :sizes Maximum hashed data buffer size (bytes) for each specified persistence profile (default: 0) def set_maximum_hash_buffer_size(opts) opts = check_params(opts,[:sizes]) super(opts) end ## # Sets the mirror states for this Persistence profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileEnabledState] :states The states indicating whether to mirror persistence records. def set_mirror_state(opts) opts = check_params(opts,[:states]) super(opts) end ## # Sets the states to indicate whether MS terminal services have been configured without # a session directory for this Persistence profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileEnabledState] :states The states for the specified Persistence profiles. def set_msrdp_without_session_directory_state(opts) opts = check_params(opts,[:states]) super(opts) end ## # Sets the persistence modes for this Persistence profile. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfilePersistenceMode] :modes The persistence modes for the specified profiles. def set_persistence_mode(opts) opts = check_params(opts,[:modes]) super(opts) end ## # Sets the UIE rules for this Persistence profile. Applicable when peristence mode # is PERSISTENCE_MODE_UIE. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileString] :rules The UIE rules for the specified Persistence profiles. def set_rule(opts) opts = check_params(opts,[:rules]) super(opts) end ## # Sets the sip_info header for this Persistence profile. Applicable when peristence # mode is PERSISTENCE_MODE_SIP. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileString] :sip_info_headers The sip_info headers for the specified Persistence profiles. Possible values are: 'Call-ID', 'To', 'From', 'SIP-ETag', 'Subject'. def set_sip_info(opts) opts = check_params(opts,[:sip_info_headers]) super(opts) end ## # Sets the pattern marking the start of the section of payload data whose hashed value # is used for the persistence value for a set of persistence profile. This is only # applicable when the persistence mode is PERSISTENCE_MODE_HASH and the hash method # is PERSISTENCE_HASH_CARP. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileString] :patterns def set_starting_hash_pattern(opts) opts = check_params(opts,[:patterns]) super(opts) end ## # Sets the timeout for this Persistence profile. The number of seconds to timeout a # persistence entry. # @rspec_example # @raise [IControl::IControl::Common::AccessDenied] raised if the client credentials are not valid. # @raise [IControl::IControl::Common::InvalidArgument] raised if one of the arguments is invalid. # @raise [IControl::IControl::Common::OperationFailed] raised if an operation error occurs. # @param [Hash] opts # @option opts [IControl::LocalLB::ProfileULong] :timeouts The idle timeouts for the specified Persistence profiles. def set_timeout(opts) opts = check_params(opts,[:timeouts]) super(opts) end ## # A structure that specifies the persistence hash method for profiles # @attr [IControl::LocalLB::ProfilePersistence::PersistenceHashMethod] value Persistence hash method # @attr [Object] default_flag How to interpret "value". For queries, if true, "value" is the parent profile's value; if false, "value" has been explicitly set. For creation and modification, if true, the parent profile's value is used to set the attribute value, and "value" is thus ignored; if false, "value" will be used. class ProfilePersistenceHashMethod < IControl::Base::Struct icontrol_attribute :value, IControl::LocalLB::ProfilePersistence::PersistenceHashMethod icontrol_attribute :default_flag, Object end ## Sequence of persistence hash methods class PersistenceHashMethodSequence < IControl::Base::Sequence ; end ## class ProfilePersistenceHashMethodSequence < IControl::Base::Sequence ; end # Persistence hash methods used for persisting connections class PersistenceHashMethod < IControl::Base::Enumeration # Invalid enumeration value PERSISTENCE_HASH_NONE = :PERSISTENCE_HASH_NONE # The hash value of the pool member index is used for persistence. PERSISTENCE_HASH_DEFAULT = :PERSISTENCE_HASH_DEFAULT # The Cache Array Routing Protocol (i.e., packet payload) is used to obtain the hash value used for persistence. PERSISTENCE_HASH_CARP = :PERSISTENCE_HASH_CARP end end end
require 'spec_helper' describe SportsSouth::Inventory do let(:credentials) { { username: 'usr', password: 'pa$$' } } before do tempfile = Tempfile.new('incremental_onhand_update') FileUtils.copy_file(FixtureHelper.get_fixture('incremental_onhand_update.xml').path, tempfile.path) allow_any_instance_of(SportsSouth::Inventory).to receive(:download_to_tempfile) { tempfile } end describe '.all' do it 'yields all items as array' do items = SportsSouth::Inventory.all(credentials) items.each_with_index do |item, index| case index when 0 expect(item[:item_identifier]).to eq('50001') expect(item[:quantity]).to eq(25) expect(item[:price]).to eq('11.89') when 1 expect(item[:item_identifier]).to eq('50002') expect(item[:quantity]).to eq(5) expect(item[:price]).to eq('110.99') when 49 expect(item[:item_identifier]).to eq('50050') expect(item[:quantity]).to eq(10) expect(item[:price]).to eq('310.62') end end expect(items.count).to eq(50) end end describe '.quantity' do it 'yields all items as array' do items = SportsSouth::Inventory.quantity(credentials) expect(items.count).to eq(50) end end end
class CreateOffers < ActiveRecord::Migration def change create_table :offers do |t| t.integer :idx, limit: 16 t.string :title, limit: 80 t.text :text t.datetime :tbegin t.datetime :tend t.decimal :price, precision: 10, scale: 2 t.string :otype, limit: 5 t.string :ostat, limit: 5 t.string :seller, limit: 40 t.integer :vcount t.binary :image t.timestamps end add_index :offers, :idx end end
require 'deliveryboy/rails/active_record' require 'deliveryboy/loggable' require 'deliveryboy/plugins' require 'email_archive' class Deliveryboy::Plugins::Archive include Deliveryboy::Plugins # Deliveryboy::Maildir needs this to load plugins properly include Deliveryboy::Loggable # to use "logger" include Deliveryboy::Rails::ActiveRecord # establish connection def initialize(config) end def handle(mail, recipient) EmailArchive.create!(:message_id => mail.message_id, :body => mail.to_s) logger.debug "[archive] #{mail.message_id}" end end
# Split a string into words, o use :- # require_relative 'String_split' # a = "This is part of the string, and this is the rest of it" # puts Splits.words(a) class Splits def self.words(string) string.downcase.scan(/[\w']+/) end end
require 'cgi' module JsClientBridge #:nodoc: module Responses #:nodoc: module Validation # Generates a validation error status response. If the first parameter is a string is will be # used as the _status options. It will also honour custom optionss as long # they don't clash with the standard ones. # # @param <String> message # An optional message. # @param <Hash> options # Custom optionss. # # @return <Hash> # The response as a Hash def respond_with_validation_error(*args) obj = args.shift options = args.last.is_a?(Hash) ? args.pop : {} # Generate our response hash and add the exceptions parameter response = if options.include?(:message) options.merge( validation_errors_to_hash(obj, options.delete(:message)) ) else options.merge( validation_errors_to_hash(obj) ) end response end # Generates a validation error status response. If the first parameter is a string is will be # used as the _status options. It will also honour custom optionss as long # they don't clash with the standard ones. # # @param <String> message # An optional message. # @param <Hash> options # Custom optionss. # # @return <String> # The response as a String encoded JSON object def render_validation(*args) obj = args.shift options = args.last.is_a?(Hash) ? args.pop : {} # Generate our response hash and add the exceptions parameter response = if options.include?(:message) options.merge( validation_errors_to_hash(obj, options.delete(:message)) ) else options.merge( validation_errors_to_hash(obj) ) end format_response(response, options) end protected def validation_errors_to_hash(data_object, message = "Sorry, we couldn't save your #{data_object.class.to_s.split('::').last}") short_type = data_object.class.to_s.split('::').last validation = { '_status' => 'validation', '_type' => data_object.class.to_s, '_short_type' => short_type, '_message' => message, 'validation' => data_object.errors.to_hash, } validation['id'] = data_object.id.to_s unless data_object.new? validation end end # module Validation end # module Responses end # module JsClientBridge
require 'spec_helper' describe QuotaPlan do describe 'price' do it 'returns optimized price for given credits' do QuotaPlan.price(50+50).should == 200 QuotaPlan.price(50+50+20).should == 250 QuotaPlan.price(20).should == 50 end end describe 'customize' do it 'looks up or creates a new plan based on input param' do new_plan = QuotaPlan.customize 100, 200 (QuotaPlan.customize 100, 200).should == new_plan end end end
module Types ViewerType = GraphQL::ObjectType.define do name "Viewer" description "The top level view of the graph" global_id_field :id interfaces [GraphQL::Relay::Node.interface] connection :chambers, -> { ChamberType.connection_type } do description "All chambers" resolve -> (obj, ctx, args) { Chamber.all } end connection :committees, -> { CommitteeType.connection_type } do description "All committees" resolve -> (obj, ctx, args) { Committee.all } end connection :hearings, -> { HearingType.connection_type } do description "All hearings" resolve -> (obj, ctx, args) { Hearing.all } end connection :bills, -> { BillType.connection_type } do description "All bills" resolve -> (obj, ctx, args) { Bill.all } end end end
class CreateProjects < ActiveRecord::Migration def change create_table :projects do |t| t.string :name t.integer :customer_id t.text :customer_contact_info t.string :status t.string :install_address t.string :budget t.string :tonnage t.text :tech_spec t.text :subsys_spec t.text :other_tech_requirement t.text :construction_requirement t.text :test_run_requirement t.text :turn_over_requirement t.date :bid_doc_available_date t.date :bid_deadline t.date :bid_opening_date t.date :contract_date t.date :production_start_date t.date :construction_finish_date t.date :install_start_date t.date :test_run_date t.date :turn_over_date t.boolean :completed, :default => false t.boolean :cancelled, :default => false t.text :note t.text :review_after t.integer :input_by_id t.timestamps end end end
# == Schema Information # # Table name: instant_bookings # # id :integer not null, primary key # first_name :string(255) # last_name :string(255) # phone_number :string(255) # email :string(255) # start_time :datetime # price :decimal(8, 2) # service_type_id :integer # requests :text # created_at :datetime not null # updated_at :datetime not null # pending :boolean default(TRUE) # appointment_id :integer # class InstantBooking < ActiveRecord::Base include ApplicationHelper include PhoneNumberHelper include ActionView::Helpers::TextHelper attr_accessible :email, :first_name, :last_name, :phone_number, :requests, :service_type_id, :start_time, :price, :address_attributes, :instant_booking_items_attributes, :start_time_date, :start_time_time, :nested_validation_user_id, :pending, :appointment_id attr_accessor :start_time_time, :start_time_date, :nested_validation_user_id belongs_to :service_type belongs_to :appointment has_one :user, :through => :service_type has_one :address, :as => :addressable, :dependent => :destroy has_many :instant_booking_items, :as => :customizable, :class_name => "CustomItem", :dependent => :destroy accepts_nested_attributes_for :address accepts_nested_attributes_for :instant_booking_items, :allow_destroy => true validates_presence_of :start_time, :start_time_time, :start_time_date validates_presence_of :email, :phone_number, :first_name, :last_name, :service_type_id validates :phone_number, :length => {:minimum => 10, :maximum => 11, :message => " must be a valid US phone number with area code"} validates :email, :format=> { :with => /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i } validate :instant_booking_sufficiently_in_advance validates :price, :format => { :with => /^\d+??(?:\.\d{0,2})?$/, :message => "must be a valid US Dollar Amount (e.g., $1.00 or $1)"}, :numericality => {:greater_than_or_equal_to => 0}, :allow_blank => true scope :pending, where(:pending => true) before_validation do |booking| if price.present? && !is_numeric?(price_before_type_cast) booking.price = format_price_for_save price_before_type_cast end if booking.start_time_date.present? && booking.start_time_time.present? booking.start_time = Time.zone.parse("#{booking.start_time_date} #{booking.start_time_time}") end booking.phone_number = phone_number.present? ? strip_nondigits_from_phone_number(phone_number) : nil booking.first_name = first_name.try(:capitalize) booking.last_name = last_name.try(:capitalize) booking.email = email.present? ? email.downcase : nil end def instant_booking_sufficiently_in_advance user = User.find_by_id(self.nested_validation_user_id) if user.present? && self.start_time.present? && user.instant_booking_profile.advance_booking_days.days.from_now.beginning_of_day > self.start_time.beginning_of_day errors[:start_time_date] << "Appointments must be booked at least #{pluralize(user.instant_booking_profile.advance_booking_days, 'days')} in advance" end end def format_price_for_save(price) price.gsub(/[^\d\.]/, '') end def start_time_time @start_time_time || start_time.try(:strftime, '%l:%M %p') end def start_time_date @start_time_date || start_time.try(:strftime, '%d/%m/%Y') end def build_all_missing_instant_booking_items(user) (user.instant_booking_fields.map(&:id) - self.instant_booking_items.map(&:custom_field_id)).each do |id| self.instant_booking_items.build(:custom_field_id => id) end end def full_name [self.first_name, self.last_name].join(' ') end end
require 'spec_helper' describe SingaporeCPFCalculator do subject(:calculator) { described_class } describe "#calculate" do let(:result) { calculator.calculate date: date, birthdate: birthdate, residency_status: residency_status, spr_start_date: spr_start_date, ordinary_wages: ordinary_wages, additional_wages: additional_wages, employee_contribution_type: employee_contribution_type, employer_contribution_type: employer_contribution_type } describe "30 years old permanent resident earning $952.00 a month" do let(:birthdate) { Date.new(1982, 2, 19) } let(:date) { Date.new(2014, 11, 15) } let(:residency_status) { "permanent_resident" } let(:spr_start_date) { Date.new(2011, 11, 14) } let(:ordinary_wages) { 700.00 } let(:additional_wages) { 252.00 } let(:employee_contribution_type) { nil } let(:employer_contribution_type) { nil } it { expect(result).to equal_cpf total: 343.00, employee: 190.00, employer: 153.00, ow: 700.0, aw: 252.00 } end describe "30 years old earning $952.00 a month before permanent residency" do let(:birthdate) { Date.new(1982, 2, 19) } let(:date) { Date.new(2014, 11, 15) } let(:residency_status) { "permanent_resident" } let(:spr_start_date) { Date.new(2015, 11, 14) } let(:ordinary_wages) { 700.00 } let(:additional_wages) { 252.00 } let(:employee_contribution_type) { "graduated" } let(:employer_contribution_type) { "graduated" } it { expect(result).to equal_cpf total: 0.00, employee: 0.00, employer: 0.00 } end end end
feature 'prints the correct birthday message' do before do allow(Date).to receive(:today).and_return(Date.new(2018,8,1)) end scenario 'it is your birthday today' do visit '/' fill_in :name, with: 'Tristan' select("1", from: "birth_day").select_option select("August", from: "birth_month").select_option click_button 'Submit' expect(page).to have_content 'Happy Birthday!' end scenario 'it is one day to your birthday' do visit '/' fill_in :name, with: 'Tristan' select("2", from: "birth_day").select_option select("August", from: "birth_month").select_option click_button 'Submit' expect(page).to have_content 'Your birthday is tomorrow!' end scenario 'there are 20 days to your birthday' do visit '/' fill_in :name, with: 'Tristan' select("21", from: "birth_day").select_option select("August", from: "birth_month").select_option click_button 'Submit' expect(page).to have_content 'There are 20 days to your birthday.' end scenario 'there are 345 days to your birthday' do visit '/' fill_in :name, with: 'Tristan' select("12", from: "birth_day").select_option select("July", from: "birth_month").select_option click_button 'Submit' expect(page).to have_content 'There are 345 days to your birthday.' end end
def add(a, b) puts "ADDING #{a} + #{b}" a + b end def subtract(a, b) puts "SUBTRACTING #{a} - #{b}" a - b end def multiply(a, b) puts "MULTIPLYING #{a} * #{b}" a * b end def divide(a, b) puts "DIVIDING #{a} / #{b}" a / b end puts "Let's do some math with just functions!" age = add(30, 5) height = subtract(78, 4) weight = multiply(90, 2) iq = divide(100, 2) puts "Age: #{age}, Height: #{height}, Weight: #{weight}, IQ: #{iq}" # A Puzzle for extra credit, type it anyway puts "Here is a puzzle." what = add(age, subtract(height, multiply(weight, divide(iq, 2)))) puts "That becomes: #{what}. Can you do it by hand?" # Study Drills # 2. (30+5)+((78-4)-((90x2)x((100/2)/2))) # 3. what = subtract(age, multiply(weight, divide(iq, add(30, height)))) puts "Now that becomes: #{what}. How do you like it?" # 4. Body Mass Index Calculator puts "BMI Calculator" puts "What is your weight in pounds?" lbs = gets.chomp.to_f puts "What is your height in inches?" inches = gets.chomp.to_f weight_kg = multiply(lbs, 0.4536) height_meters = multiply(inches, 0.0254) bmi = divide(weight_kg, multiply(height_meters, height_meters)) puts "Your BMI is #{bmi}."
#! /usr/local/bin/ruby require 'eventmachine' module TelnetServer def post_init @buffer = "" @prompt = "prompt>" warn "Server: Client connected." send_prompt end def send_prompt send_data @prompt end def receive_data data @buffer << data @buffer.each_line do |cmd| case cmd when /foo/ warn "Server: Client sent command 'foo'." @buffer = "" send_data <<OUT >>>> This is the first output line of the command 'foo'. >>>> This is the second output line of the command 'foo'. >>>> This is the third output line of the command 'foo'. OUT send_prompt warn "Server: Sent output and prompt." when /bar/ warn "Server: Client sent command 'bar'." @buffer = "" EventMachine.add_timer 4 do send_data <<OUT >>>> First line of the command 'bar'. >>>> Second line of the command 'bar'. >>>> Third line of the command 'bar'. OUT send_prompt end when /quit/ warn "Server: Client sent command 'quit'." close_connection end end end def unbind warn "Server: Client disconnected." end end EventMachine.run do EventMachine.start_server 'localhost', 8000, TelnetServer end
class ChangeFolloerIdName < ActiveRecord::Migration def change rename_column :followings, :follower_id, :followed_id end end
module Shipcloud module Operations module Create module ClassMethods # Creates a new object # # @param [Hash] attributes The attributes of the created object # @param \[String\] optional api_key The api key. If no api key is given, Shipcloud.api_key # will be used for the request def create(attributes, api_key: nil) response = Shipcloud.request(:post, base_url, attributes, api_key: api_key) if create_response_root response = response.fetch(create_response_root, {}) end self.new(response) end end def self.included(base) base.extend(ClassMethods) end end end end
class DrawCommand attr_reader :drawable, :position def initialize(drawable, position:) @drawable = drawable @position = position end def execute drawable.draw(position[:x], position[:y]) end end
require 'withings-sdk/measures' module WithingsSDK class MeasurementGroup < Base # Types of body measurements collected by Withings devices and supported # by this gem. See http://oauth.withings.com/api/doc#api-Measure-get_measure # for details. TYPES = { 1 => WithingsSDK::Measure::Weight, 4 => WithingsSDK::Measure::Height, 5 => WithingsSDK::Measure::FatFreeMass, 6 => WithingsSDK::Measure::FatRatio, 8 => WithingsSDK::Measure::FatMassWeight, 11 => WithingsSDK::Measure::Pulse } # Create a new instance with a collection of measurements of the appropriate # WithingsSDK::Measure type. # # @param attrs [Hash] # @return [WithingsSDK::MeasurementGroup] def initialize(attrs = {}) super(attrs) return if attrs['measures'].nil? @measures = attrs['measures'].collect do |measurement| klass = TYPES[measurement['type']] klass.new(measurement) unless klass.nil? end.reject { |obj| obj.nil? } end end end
# -*- coding: utf-8 -*- require 'write_xlsx/package/xml_writer_simple.rb' module Writexlsx class Drawing attr_writer :embedded def initialize @writer = Package::XMLWriterSimple.new @drawings = [] @embedded = false @orientation = false end def xml_str @writer.string end def set_xml_writer(filename) @writer.set_xml_writer(filename) end # # Assemble and write the XML file. # def assemble_xml_file @writer.xml_decl # Write the xdr:wsDr element. write_drawing_workspace if @embedded index = 0 @drawings.each do |dimensions| # Write the xdr:twoCellAnchor element. index += 1 write_two_cell_anchor(index, *(dimensions.flatten)) end else index = 0 # Write the xdr:absoluteAnchor element. index += 1 write_absolute_anchor(index) end @writer.end_tag('xdr:wsDr') @writer.crlf @writer.close end # # Add a chart or image sub object to the drawing. # def add_drawing_object(*args) @drawings << args end private # # Write the <xdr:wsDr> element. # def write_drawing_workspace schema = 'http://schemas.openxmlformats.org/drawingml/' xmlns_xdr = "#{schema}2006/spreadsheetDrawing" xmlns_a = "#{schema}2006/main" attributes = [ 'xmlns:xdr', xmlns_xdr, 'xmlns:a', xmlns_a ] @writer.start_tag('xdr:wsDr', attributes) end # # Write the <xdr:twoCellAnchor> element. # def write_two_cell_anchor(*args) index, type, col_from, row_from, col_from_offset, row_from_offset, col_to, row_to, col_to_offset, row_to_offset, col_absolute, row_absolute, width, height, description = args attributes = [] # Add attribute for images. attributes << :editAs << 'oneCell' if type == 2 @writer.start_tag('xdr:twoCellAnchor', attributes) # Write the xdr:from element. write_from(col_from, row_from, col_from_offset, row_from_offset) # Write the xdr:from element. write_to(col_to, row_to, col_to_offset, row_to_offset) if type == 1 # Write the xdr:graphicFrame element for charts. write_graphic_frame(index) else # Write the xdr:pic element. write_pic(index, col_absolute, row_absolute, width, height, description) end # Write the xdr:clientData element. write_client_data @writer.end_tag('xdr:twoCellAnchor') end # # Write the <xdr:from> element. # def write_from(col, row, col_offset, row_offset) @writer.start_tag('xdr:from') # Write the xdr:col element. write_col(col) # Write the xdr:colOff element. write_col_off(col_offset) # Write the xdr:row element. write_row(row) # Write the xdr:rowOff element. write_row_off(row_offset) @writer.end_tag('xdr:from') end # # Write the <xdr:to> element. # def write_to(col, row, col_offset, row_offset) @writer.start_tag('xdr:to') # Write the xdr:col element. write_col(col) # Write the xdr:colOff element. write_col_off(col_offset) # Write the xdr:row element. write_row(row) # Write the xdr:rowOff element. write_row_off(row_offset) @writer.end_tag('xdr:to') end # # Write the <xdr:col> element. # def write_col(data) @writer.data_element('xdr:col', data) end # # Write the <xdr:colOff> element. # def write_col_off(data) @writer.data_element('xdr:colOff', data) end # # Write the <xdr:row> element. # def write_row(data) @writer.data_element('xdr:row', data) end # # Write the <xdr:rowOff> element. # def write_row_off(data) @writer.data_element('xdr:rowOff', data) end # # Write the <xdr:graphicFrame> element. # def write_graphic_frame(index) macro = '' attributes = ['macro', macro] @writer.start_tag('xdr:graphicFrame', attributes) # Write the xdr:nvGraphicFramePr element. write_nv_graphic_frame_pr(index) # Write the xdr:xfrm element. write_xfrm # Write the a:graphic element. write_atag_graphic(index) @writer.end_tag('xdr:graphicFrame') end # # Write the <xdr:nvGraphicFramePr> element. # def write_nv_graphic_frame_pr(index) @writer.start_tag('xdr:nvGraphicFramePr') # Write the xdr:cNvPr element. write_c_nv_pr( index + 1, "Chart #{index}" ) # Write the xdr:cNvGraphicFramePr element. write_c_nv_graphic_frame_pr @writer.end_tag('xdr:nvGraphicFramePr') end # # Write the <xdr:cNvPr> element. # def write_c_nv_pr(id, name, descr = nil) attributes = [ 'id', id, 'name', name ] # Add description attribute for images. attributes << 'descr' << descr if descr @writer.empty_tag('xdr:cNvPr', attributes) end # # Write the <xdr:cNvGraphicFramePr> element. # def write_c_nv_graphic_frame_pr if @embedded @writer.empty_tag('xdr:cNvGraphicFramePr') else @writer.start_tag('xdr:cNvGraphicFramePr') # Write the a:graphicFrameLocks element. write_a_graphic_frame_locks @writer.end_tag('xdr:cNvGraphicFramePr') end end # # Write the <a:graphicFrameLocks> element. # def write_a_graphic_frame_locks no_grp = 1 attributes = ['noGrp', no_grp ] @writer.empty_tag('a:graphicFrameLocks', attributes) end # # Write the <xdr:xfrm> element. # def write_xfrm @writer.start_tag('xdr:xfrm') # Write the xfrmOffset element. write_xfrm_offset # Write the xfrmOffset element. write_xfrm_extension @writer.end_tag('xdr:xfrm') end # # Write the <a:off> xfrm sub-element. # def write_xfrm_offset x = 0 y = 0 attributes = [ 'x', x, 'y', y ] @writer.empty_tag('a:off', attributes) end # # Write the <a:ext> xfrm sub-element. # def write_xfrm_extension x = 0 y = 0 attributes = [ 'cx', x, 'cy', y ] @writer.empty_tag('a:ext', attributes) end # # Write the <a:graphic> element. # def write_atag_graphic(index) @writer.start_tag('a:graphic') # Write the a:graphicData element. write_atag_graphic_data(index) @writer.end_tag('a:graphic') end # # Write the <a:graphicData> element. # def write_atag_graphic_data(index) uri = 'http://schemas.openxmlformats.org/drawingml/2006/chart' attributes = ['uri', uri] @writer.start_tag('a:graphicData', attributes) # Write the c:chart element. write_c_chart("rId#{index}") @writer.end_tag('a:graphicData') end # # Write the <c:chart> element. # def write_c_chart(r_id) schema = 'http://schemas.openxmlformats.org/' xmlns_c = "#{schema}drawingml/2006/chart" xmlns_r = "#{schema}officeDocument/2006/relationships" attributes = [ 'xmlns:c', xmlns_c, 'xmlns:r', xmlns_r, 'r:id', r_id ] @writer.empty_tag('c:chart', attributes) end # # Write the <xdr:clientData> element. # def write_client_data @writer.empty_tag('xdr:clientData') end # # Write the <xdr:pic> element. # def write_pic(index, col_absolute, row_absolute, width, height, description) @writer.start_tag('xdr:pic') # Write the xdr:nvPicPr element. write_nv_pic_pr(index, description) # Write the xdr:blipFill element. write_blip_fill(index) # Write the xdr:spPr element. write_sp_pr(col_absolute, row_absolute, width, height) @writer.end_tag('xdr:pic') end # # Write the <xdr:nvPicPr> element. # def write_nv_pic_pr(index, description) @writer.start_tag('xdr:nvPicPr') # Write the xdr:cNvPr element. write_c_nv_pr( index + 1, "Picture #{index}", description ) # Write the xdr:cNvPicPr element. write_c_nv_pic_pr @writer.end_tag('xdr:nvPicPr') end # # Write the <xdr:cNvPicPr> element. # def write_c_nv_pic_pr @writer.start_tag('xdr:cNvPicPr') # Write the a:picLocks element. write_a_pic_locks @writer.end_tag('xdr:cNvPicPr') end # # Write the <a:picLocks> element. # def write_a_pic_locks no_change_aspect = 1 attributes = ['noChangeAspect', no_change_aspect] @writer.empty_tag('a:picLocks', attributes) end # # Write the <xdr:blipFill> element. # def write_blip_fill(index) @writer.start_tag('xdr:blipFill') # Write the a:blip element. write_a_blip(index) # Write the a:stretch element. write_a_stretch @writer.end_tag('xdr:blipFill') end # # Write the <a:blip> element. # def write_a_blip(index) schema = 'http://schemas.openxmlformats.org/officeDocument/' xmlns_r = "#{schema}2006/relationships" r_embed = "rId#{index}" attributes = [ 'xmlns:r', xmlns_r, 'r:embed', r_embed ] @writer.empty_tag('a:blip', attributes) end # # Write the <a:stretch> element. # def write_a_stretch @writer.start_tag('a:stretch') # Write the a:fillRect element. write_a_fill_rect @writer.end_tag('a:stretch') end # # Write the <a:fillRect> element. # def write_a_fill_rect @writer.empty_tag('a:fillRect') end # # Write the <xdr:spPr> element. # def write_sp_pr(col_absolute, row_absolute, width, height) @writer.start_tag('xdr:spPr') # Write the a:xfrm element. write_a_xfrm(col_absolute, row_absolute, width, height) # Write the a:prstGeom element. write_a_prst_geom @writer.end_tag('xdr:spPr') end # # Write the <a:xfrm> element. # def write_a_xfrm(col_absolute, row_absolute, width, height) @writer.start_tag('a:xfrm') # Write the a:off element. write_a_off( col_absolute, row_absolute ) # Write the a:ext element. write_a_ext( width, height ) @writer.end_tag('a:xfrm') end # # Write the <a:off> element. # def write_a_off(x, y) attributes = [ 'x', x, 'y', y ] @writer.empty_tag('a:off', attributes) end # # Write the <a:ext> element. # def write_a_ext(cx, cy) attributes = [ 'cx', cx, 'cy', cy ] @writer.empty_tag('a:ext', attributes) end # # Write the <a:prstGeom> element. # def write_a_prst_geom prst = 'rect' attributes = ['prst', prst] @writer.start_tag('a:prstGeom', attributes) # Write the a:avLst element. write_a_av_lst @writer.end_tag('a:prstGeom') end # # Write the <a:avLst> element. # def write_a_av_lst @writer.empty_tag('a:avLst') end end end
class Taxi < ActiveRecord::Base #a taxi can have many passengers has_many :rides has_many :passengers, through: :rides end #:tags, through: :posts_tags
def english_number(number) return "Please enter a positive number" if number < 0 return "zero" if number == 0 return "Please enter a number smaller than 1,000,000,000,000,000" if number >= 1000000000000000 number_string = "" ones = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] tens = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"] teens = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"] hundreds = ["one hundred", "two hundred", "three hundred", "four hundred", "five hundred", "six hundred", "seven hundred", "eight hundred", "nine hundred"] if number % 1000000000000000 / 1000000000000 > 0 if (number / 100000000000000) > 0 number_string << hundreds[(number / 100000000000000) - 1] if number % 100000000000000 / 1000000000000 > 0 number_string << " and " end end if number % 100000000000000 / 10000000000000 == 1 number_string << teens[number % 10000000000000 / 1000000000000] elsif number % 100000000000000 / 10000000000000 > 0 number_string << tens[(number % 100000000000000 / 10000000000000) - 2] end if number % 100000000000000 / 10000000000000 == 1 number_string << "" elsif number % 10000000000000 / 1000000000000 == 0 number_string << "" elsif (number % 100000000000000 / 10000000000000 > 1) && (number % 10000000000000 / 1000000000000 > 0) number_string << "-" + ones[number % 10000000000000 / 1000000000000 - 1] elsif (number % 100000000000000 / 10000000000000 == 0) && (number % 10000000000000 / 1000000000000 > 0) number_string << ones[number % 10000000000000 / 1000000000000 - 1] end number_string << " trillion " end if number % 1000000000000 / 1000000000 > 0 if (number % 1000000000000 / 100000000000) > 0 number_string << hundreds[(number % 1000000000000 / 100000000000) - 1] if number % 100000000000 / 1000000000 > 0 number_string << " and " end end if number % 100000000000 / 10000000000 == 1 number_string << teens[number % 10000000000 / 1000000000] elsif number % 100000000000 / 10000000000 > 0 number_string << tens[(number % 100000000000 / 10000000000) - 2] end if number % 100000000000 / 10000000000 == 1 number_string << "" elsif number % 10000000000 / 1000000000 == 0 number_string << "" elsif (number % 100000000000 / 10000000000 > 1) && (number % 10000000000 / 1000000000 > 0) number_string << "-" + ones[number % 10000000000 / 1000000000 - 1] elsif (number % 100000000000 / 10000000000 == 0) && (number % 10000000000 / 1000000000 > 0) number_string << ones[number % 10000000000 / 1000000000 - 1] end number_string << " billion " end if number % 1000000000 / 1000000 > 0 if (number % 1000000000 / 100000000) > 0 number_string << hundreds[(number % 1000000000 / 100000000) - 1] if number % 100000000 / 1000000 > 0 number_string << " and " end end if number % 100000000 / 10000000 == 1 number_string << teens[number % 10000000 / 1000000] elsif number % 100000000 / 10000000 > 0 number_string << tens[(number % 100000000 / 10000000) - 2] end if number % 100000000 / 10000000 == 1 number_string << "" elsif number % 10000000 / 1000000 == 0 number_string << "" elsif (number % 100000000 / 10000000 > 1) && (number % 10000000 / 1000000 > 0) number_string << "-" + ones[number % 10000000 / 1000000 - 1] elsif (number % 100000000 / 10000000 == 0) && (number % 10000000 / 1000000 > 0) number_string << ones[number % 10000000 / 1000000 - 1] end number_string << " million " end if number % 1000000 / 1000 > 0 if (number % 1000000 / 100000) > 0 number_string << hundreds[(number % 1000000 / 100000) - 1] if number % 100000 / 1000 > 0 number_string << " and " end end if number % 100000 / 10000 == 1 number_string << teens[number % 10000 / 1000] elsif number % 100000 / 10000 > 0 number_string << tens[(number % 100000 / 10000) - 2] end if number % 100000 / 10000 == 1 number_string << "" elsif number % 10000 / 1000 == 0 number_string << "" elsif (number % 100000 / 10000 > 1) && (number % 10000 / 1000 > 0) number_string << "-" + ones[number % 10000 / 1000 - 1] elsif (number % 100000 / 10000 == 0) && (number % 10000 / 1000 > 0) number_string << ones[number % 10000 / 1000 - 1] end number_string << " thousand " end if number % 1000 > 0 if (number % 1000 / 100) > 0 number_string << hundreds[(number % 1000 / 100) - 1] if number % 100000 / 1000 > 0 number_string << " and " end elsif (number % 1000 / 100 == 0) && (number >= 1000) number_string << "and " end if number % 100 / 10 == 1 number_string << teens[number % 10] elsif number % 100 / 10 > 0 number_string << tens[(number % 100 / 10) - 2] end if number % 100 / 10 == 1 number_string << "" elsif number % 10 == 0 number_string << "" elsif (number % 100 / 10 > 1) && (number % 10 > 0) number_string << "-" + ones[(number % 10) - 1] elsif (number % 100 / 10 == 0) && (number % 10 > 0) number_string << ones[number % 10 - 1] end end return number_string end def bottles_of_beer number return "Number must be positive" if number <= 0 while number > 0 puts english_number(number).capitalize + " bottles of beer on the wall," puts english_number(number).capitalize + " bottles of beer." puts "Take one down and pass it around," number -= 1 puts english_number(number).capitalize + " bottles of beer on the wall!" puts " " end end
class Forecast < ApplicationRecord has_many :weather, dependent: :destroy has_one :location, dependent: :destroy validates :request_location, :current_weather_code, :date_time, :current_temperature, :temperature_unit, :current_weather_text, presence: true attr_accessor :temp_unit end
module Api::V1 class SprintsController < BaseApiController before_action -> { authenticate_role! [:team_lead, :admin] }, only: [:update] def index render json: Sprint.all, each_serializer: Api::V1::SprintSerializer end def update sprint = Sprint.find(params[:data][:id]) if sprint.update_attributes(sprint_params) render json: sprint, serializer: Api::V1::SprintSerializer else render json: sprint.json_api_format_errors, status: 422 end end private def sprint_params params.require(:data).permit(attributes: [:start_date, :end_date]) end end end
require 'minimed_rf' require 'minimed_rf/string_utils' require 'erb' namespace :ios do desc "Generate list of history types" task :history_types do MinimedRF::PumpEvents.constants.each do |event_class| klazz = MinimedRF::PumpEvents.const_get(event_class) next if klazz == MinimedRF::PumpEvents::Base name = klazz.to_s.split("::").last.underscore.upcase code = "0x%02x" % klazz.event_type_code puts "#define MM_HISTORY_#{name} #{code}" end end desc "Generate Objective-C classes for pump events" task :classes, [:output_dir] do |t, args| output_dir = args[:output_dir] if output_dir.nil? raise "Need to supply output directory!" end template_m = File.read(File.expand_path('../history_entry_objc.m.erb', __FILE__)) template_h = File.read(File.expand_path('../history_entry_objc.h.erb', __FILE__)) MinimedRF::PumpEvents.constants.each do |event_class| klazz = MinimedRF::PumpEvents.const_get(event_class) next if klazz == MinimedRF::PumpEvents::Base class_name = "PHE" + klazz.to_s.split("::").last event_type_code = "0x%02x" % klazz.event_type_code length = klazz.new("0000", MinimedRF::Model522.new).bytesize h_file = output_dir + "/" + class_name + ".h" if !File.exists?(h_file) File.open(h_file, "w+") do |f| f.write(ERB.new(template_h).result(binding)) end end m_file = output_dir + "/" + class_name + ".m" if !File.exists?(m_file) File.open(m_file, "w+") do |f| f.write(ERB.new(template_m).result(binding)) end end end end end
class CreateDictionaries < ActiveRecord::Migration def change create_table :dictionaries do |t| t.string :type t.string :item t.boolean :delflag t.decimal :priority t.string :remark t.timestamps end end end
require 'rails_helper' RSpec.describe Recruiter::ApplicantDetailsController, type: :controller do before do @recruiter = FactoryGirl.create :recruiter sign_in @recruiter end def set_applicant_detail @applicant_detail = FactoryGirl.create :applicant_detail end describe "GET #index" do context "successfully" do before do 5.times { FactoryGirl.create :applicant_detail } get :index end it "render index template" do expect(response).to render_template :index end it "return all details of applicants" do expect(assigns[:applicant_details].count).to eq 5 end end end describe "GET #show" do context "successfully" do before do set_applicant_detail get :show, id: @applicant_detail end it "should display applicant's detail" do expect(assigns[:applicant_detail]).to eq @applicant_detail end it "should render show template" do expect(response).to render_template :show end end end describe "GET #new" do context "successfully" do before { get :new } it "render template" do expect(response).to render_template :new end end end describe "POST #create" do context "successfully" do before do @applicant_detail_attributes = FactoryGirl.attributes_for :applicant_detail end it "should create and save applicant" do expect{ post :create, { applicant_detail: @applicant_detail_attributes } }.to change(ApplicantDetail, :count).by(1) end it "should display flash message" do message = "application successfully created." post :create, { applicant_detail: @applicant_detail_attributes } expect(flash[:success]).to eq message end it "should redirect to applicant_detail just created" do post :create, { applicant_detail: @applicant_detail_attributes } expect(response).to redirect_to recruiter_applicant_detail_url(assigns[:applicant_detail].id) end end context "unsuccessfully" do before do @invalid_attributes = FactoryGirl.attributes_for :applicant_detail @invalid_attributes[:name] = "" end it "applicant details not saved" do expect{ post :create, { applicant_detail: @invalid_attributes } }.not_to change(ApplicantDetail, :count) end it "displays alert flash messgae" do post :create, { applicant_detail: @invalid_attributes } message = "something went wrong. could not create application" expect(flash[:alert]).to eq message end it "should render new template" do post :create, { applicant_detail: @invalid_attributes } expect(response).to render_template :new end end end describe "GET #edit" do before do set_applicant_detail end context "successfully" do before do get :edit, id: @applicant_detail.id end it "renders edit template" do expect(response).to render_template :edit end end end describe "PUT/PATCH #update" do before do set_applicant_detail end context "successfully" do before { patch :update, { id: @applicant_detail.id, applicant_detail: { name: "Paa Yaw" } } } it "it updates name" do expect(assigns[:applicant_detail].name).to eq "Paa Yaw" end it "displays flash success message" do message = "application successfully updated." expect(flash[:success]).to eq message end it "should redirect to updated applicant's detail" do expect(response).to redirect_to recruiter_applicant_detail_url(@applicant_detail.id) end end context "update failed" do before do patch :update, { id: @applicant_detail.id, applicant_detail: { experience: ""} } end it "should display alert flash message" do message = "something went wrong. update failed" expect(flash[:alert]).to eq message end it "renders edit template" do expect(response).to render_template :edit end end end describe "GET #match_job_description" do before { set_applicant_detail } context "successfully" do before do 5.times { FactoryGirl.create :requirement } get :match_job_description, id: @applicant_detail.id end it "should render match_job_description template" do expect(response).to render_template :match_job_description end it "display applicant details" do expect(assigns[:applicant_detail]).to eq @applicant_detail end it "displays 5 requirements" do expect(assigns[:requirements].uniq.count).to eq 5 end end end end
# frozen_string_literal: true module SystemTestHelper def clear_cookies browser = Capybara.current_session.driver.browser if browser.respond_to?(:clear_cookies) # Rack::MockSession browser.clear_cookies elsif browser.respond_to?(:manage) && browser.manage.respond_to?(:delete_all_cookies) # Selenium::WebDriver browser.manage.delete_all_cookies else raise "Don't know how to clear cookies. Weird driver?" end end def visit_with_login(path, redirected_path: nil, user: :uwe) uri = URI.parse(path) key_param = { 'key' => users(user).generate_security_token(:login) } uri.query = (uri.query ? Rack::Utils.parse_query(uri.query).merge(key_param) : key_param).to_query visit uri.to_s uri.fragment = nil assert_current_path redirected_path || uri.to_s end def login(user = :uwe) visit_with_login '/', user: user end def wait_for_ajax with_retries { assert page.evaluate_script('jQuery.active').zero? } end def all(*args, **opts) super(*args, **{ wait: false }.merge(opts)) end def close_alerts all('.alert button.close').each(&:click) assert has_no_css?('.alert button.close') end def open_menu close_alerts find('#navBtn', wait: 30).click end def open_menu_section(section_title) open_menu section = find('#main-menu > h1', text: section_title) section.click find(section['data-bs-target']) end def click_menu(menu_item, section:) section = open_menu_section(section) link = section.find(:link, menu_item) with_retries(label: 'click menu') { link.click } end def select_from_chosen(item_text, options) field = find_field(options[:from], visible: false, disabled: :all) find("##{field[:id]}_chosen").click find("##{field[:id]}_chosen ul.chosen-results li", text: item_text).click end end
class LinksController < ApplicationController before_action :authenticate_user! before_action :initialize_link, only: %i[edit update destroy share hide] def index @links = current_user.links end def new @link = Link.new end def create @link = current_user.links.new(link_params) if @link.save redirect_to links_path, notice: 'Link was successfully created!' else render :new end end def edit; end def update if @link.update_attributes(link_params) redirect_to links_path, notice: 'Link was successfully updated.' else render :edit end end def destroy @link.destroy redirect_to links_path, alert: 'Link was successfully deleted.' end def share @link.share! redirect_to links_path, notice: 'You successfully share link!' end def hide @link.hide! redirect_to links_path, alert: 'You successfully hide link.' end private def link_params params.require(:link).permit( :href, :description, :tag_list ) end def initialize_link @link = Link.find(params[:id]) end end
class SessionsController < ApplicationController skip_before_action :login_required, :only => [:new, :create] def new @user = User.new end def create user = User.find_by_email(session_params[:email]) if user && user.authenticate(session_params[:password]) session[:user_id] = user.id flash[:notice] = "Welcome, #{user.email}!" redirect_to statuses_path else flash[:alert] = "Please log in again" render "new" end end def destroy session[:user_id] = nil redirect_to root_path end private def login(user) session[:user_id] = nil end def session_params params.require(:session).permit(:email, :password) end end
#!/usr/bin/env ruby require 'net/http' require 'net/https' require 'openssl' require 'base64' require 'rexml/document' # We have enough of a minimal parser to get by without the JSON gem. # However, if it's available we may as well use it. begin require 'json' rescue LoadError end # Escape URI form components. # URI.encode_www_form_component doesn't exist on Ruby 1.8, so we fall back to # URI.encode + gsub def uri_encode(component) if URI.respond_to? :encode_www_form_component URI.encode_www_form_component(component) else URI.encode(component).gsub('=', '%3D').gsub(':', '%3A').gsub('/', '%2F').gsub('+', '%2B') end end # If the JSON gem was loaded, use JSON.parse otherwise use the inbuilt mini parser def parse_json_object(input) if defined? JSON JSON.parse(input) else json_objparse(input) end end # A mini parser capable of parsing unnested JSON objects. # A couple of the http://169.254.169.254/ pages return simple JSON # in the form of: # { # "KeyA" : "ValueA", # "KeyB" : "ValueB" # } # Which this should be able to handle. We should still use the JSON library if it's available though def json_objparse(input) input = input.strip # Copy, don't strip! the source string unless input.start_with?('{') && input.end_with?('}') raise "not an object" end body = input[1..-2].gsub("\n", ' ') # Easier than dealing with newlines in regexen if body.empty? return {} end obj = {} until body.nil? || body =~ /^\s*$/ next if body.match(/^\s*"([^"]*)"\s*:\s*("[^"]*"|\d+\.\d+|\d+|null|true|false)\s*(?:,(.*)|($))/) do |md| key = md[1] if obj.has_key? key raise "Duplicate key #{key}" end case md[2] when 'null' obj[key] = nil when 'true' obj[key] = true when 'false' obj[key] = false when /^"[^"]*"$/ obj[key] = md[2][1..-2] when /^\d+\.\d+$/ obj[key] = md[2].to_f when /^\d+$/ obj[key] = md[2].to_i end body = md[3] true end raise "Parsing failed at #{body.strip.inspect}" end obj end # The instance document tells us our instance id, region, etc def get_instance_document url = URI.parse('http://169.254.169.254/latest/dynamic/instance-identity/document') response = Net::HTTP.get_response(url) return nil if response.code != "200" return parse_json_object(response.body) end # If an IAM role is available for the instance, we will attempt to query it. # We return an empty Hash on failure. Keys may be available via enviroment # variables as a fallback. def get_instance_role url = URI.parse('http://169.254.169.254/latest/meta-data/iam/security-credentials/') response = Net::HTTP.get_response(url) return {} if response.code != "200" body = response.body role = body.lines.first response = Net::HTTP::get_response(url+role) return {} if response.code != "200" role = parse_json_object(response.body) end # Sign and send a request to the AWS REST API. Method is defined as an "Action" parameter. # parameters is an array because order is important for the signing process. def query(parameters, endpoint, access_key, secret_key, token = nil) timestamp = Time.now.utc.strftime('%Y-%m-%dT%H:%M:%SZ') parameters += [ ['AWSAccessKeyId', access_key ], ['SignatureVersion', '2' ], ['SignatureMethod', 'HmacSHA256' ], ['Timestamp', timestamp ], ] if token parameters.push(['SecurityToken', token]) end sorted_parameters = parameters.sort_by {|k,v| k } sorted_params_string = sorted_parameters.map {|k,v| "#{uri_encode(k)}=#{uri_encode(v)}" }.join('&') params_string = parameters.map {|k,v| "#{uri_encode(k)}=#{uri_encode(v)}" }.join('&') canonical_query = [ 'GET', endpoint, '/', sorted_params_string ].join("\n") sha256 = OpenSSL::Digest::Digest.new('sha256') signature = OpenSSL::HMAC.digest(sha256, secret_key, canonical_query) signature = Base64.encode64(signature).strip signature = uri_encode(signature) req_path = "/?#{params_string}&Signature=#{signature}" retries = 5 begin req = Net::HTTP::Get.new(req_path) http = Net::HTTP.new(endpoint, 443) http.use_ssl = true response = http.start { http.request(req) } response rescue StandardError, Timeout::Error => e Facter.debug("Error querying 'http://#{endpoint}/?#{sorted_params_string}' - retries left: #{retries}") sleep 3 retry if (retries -= 1) > 0 end end # Queries CFN endpoint for stack info def query_cfn(stack_name, endpoint, access_key, secret_key, token = nil) parameters = [ ['Action', 'DescribeStacks' ], ['StackName', stack_name ], ['Version', '2010-05-15' ], ] response = query(parameters, endpoint, access_key, secret_key, token) if response.code != "200" Facter.debug("DescribeStacks returned #{response.code} #{response.message}") return {} end doc = REXML::Document.new(response.body) cfn = {} # Stack Parameters doc.get_elements('//Parameters/member').each do |item| key = item.get_elements('ParameterKey')[0].text value = item.get_elements('ParameterValue')[0].text cfn['cfn_stack_param_' + key] = value end return cfn end # Queries the tags from the provided EC2 instance id. def query_instance(instance_id, endpoint, access_key, secret_key, token = nil) parameters = [ ['Action', 'DescribeInstances' ], ['InstanceId.1', instance_id ], ['Version', '2014-10-01' ], ] response = query(parameters, endpoint, access_key, secret_key, token) if response.code != "200" Facter.debug("DescribeInstances returned #{response.code} #{response.message}") return {} end doc = REXML::Document.new(response.body) tags = {} doc.get_elements('//tagSet/item').each do |item| key = item.get_elements('key')[0].text key.gsub!(':','_') value = item.get_elements('value')[0].text tags["ec2_tag_#{key}"] = value end lifecycle = doc.get_elements('//instanceLifecycle')[0] if ! lifecycle.nil? tags['ec2_lifecycle'] = lifecycle.text end return tags end # Queries the min/max/desired size of the provided autoscaling group. def query_autoscale_group(group_id, endpoint, access_key, secret_key, token) parameters = [ ['Action', 'DescribeAutoScalingGroups' ], ['AutoScalingGroupNames.member.1', group_id ], ['Version', '2011-01-01' ], ] response = query(parameters, endpoint, access_key, secret_key, token) if response.code != "200" Facter.debug("DescribeAutoScalingGroups returned #{response.code} #{response.message}") return {} end doc = REXML::Document.new(response.body) # Note: These params get merged into the facts Hash, so the keys should match the fact names params = {} min_size_elem = doc.get_elements('//MinSize')[0] if min_size_elem.nil? Facter.debug("No MinSize found for autoscaling group #{group_id}") return nil else params['autoscaling_min_size'] = min_size_elem.text end max_size_elem = doc.get_elements('//MaxSize')[0] if max_size_elem.nil? Facter.debug("No MaxSize found for autoscaling group #{group_id}") return nil else params['autoscaling_max_size'] = max_size_elem.text end desired_cap_elem = doc.get_elements('//DesiredCapacity')[0] if desired_cap_elem.nil? Facter.debug("No DesiredCapacity found for autoscaling group #{group_id}") return nil else params['autoscaling_desired_capacity'] = desired_cap_elem.text end elbs = [] elb_elem = doc.get_elements('//LoadBalancerNames/member').each do |item| elbs << item.text end if elbs params['autoscaling_elbs'] = elbs end # Get the ASG tags. doc.get_elements('//Tags/member').each do |item| key = item.get_elements('Key')[0].text next if key.start_with?('aws:') key.gsub!(':','_') value = item.get_elements('Value')[0].text params["autoscaling_tag_#{key}"] = value end return params end # Look for our EC2 instance ID, then query the tags assigned to the instance. # If there is an autoscaling group tag (aws:autoscaling:groupName), also query # the autoscaling group min/max/desired size parameters. def check_facts cache_file = '/tmp/ec2_facts.json' if File.exist?(cache_file) if ( ( Time.now - File.stat(cache_file).mtime ).to_i < [ 43200, 86400 ].sample ) Facter.debug( "reading from cache: " + cache_file ) open(cache_file, 'r') do |io| facts = parse_json_object(io.read.strip) facts.each do |fact, value| Facter.add(fact) do setcode { value } end end end return end end facts = {} open('/etc/ec2_version', 'r') do |io| facts['ec2_version'] = io.read.strip end instance = get_instance_document if instance.nil? Facter.debug("Didn't get instance document from http://169.254.169.254/latest/dynamic/instance-identity/document") return end instance_id = instance['instanceId'] region = instance['region'] role = get_instance_role access_key = role['AccessKeyId'] || ENV['AWS_ACCESS_KEY_ID'] secret_key = role['SecretAccessKey'] || ENV['AWS_SECRET_ACCESS_KEY'] token = role['Token'] if access_key.nil? || secret_key.nil? Facter.debug("No authentication key available") return end tags = query_instance(instance_id, "ec2.#{region}.amazonaws.com", access_key, secret_key, token) tags.each do |tag, value| facts[tag] = value end if tags.has_key? 'ec2_tag_aws_autoscaling_groupName' autoscale_group = tags['ec2_tag_aws_autoscaling_groupName'] facts['autoscaling_group_name'] = autoscale_group asg_params = query_autoscale_group(autoscale_group, "autoscaling.#{region}.amazonaws.com", access_key, secret_key, token) facts = facts.merge(asg_params) end if tags.has_key? 'aws:cloudformation:stack-name' cfn_stack_name = tags['aws:cloudformation:stack-name'] facts['cloudformation_stack_name'] = cfn_stack_name # Grab CFN parameters cfn_data = query_cfn(cfn_stack_name, "cloudformation.#{region}.amazonaws.com", access_key, secret_key, token) facts = facts.merge(cfn_data) end File.open(cache_file, "w", 0644) { |f| f.write(facts.to_json) } facts.each do |fact, value| Facter.add(fact) do setcode { value } end end rescue StandardError => e Facter.debug("Unhandled #{e.class}: #{e.message}") end # This file seems to exist on our EC2 instances. There may be a better way to # determine if we are running on EC2. # We mostly want to avoid waiting for http://169.254.169.254/ to time out if we are not on EC2. if File.exists?('/etc/ec2_version') check_facts end
module Rubel module Core # q - The String or Proc to be executed def execute(q = nil) if q.is_a?(::String) q = Rubel.sanitized_proc(q) end instance_exec(&q) end alias query execute # Returns method name as a Symbol if args are empty or a Message which # will call `name` with your evaluated `args` [1]. # # @example # r$: MAP( [foo, bar], to_s ) # # First it converts foo, bar, to_s to symbols. Then MAP will call :to_s on [:foo, :bar] # # Thus it is equivalent to: [:foo, :bar].map(&:to_s) # # @example # # r$: MAP( [0.123456, 0.98765], # the objects # r$: round( SUM(1,2) ) ) # instruction to round by 3. # r$: # => #<Rubel::Message round(3)> # # @return [Proc] A Proc with a method call to *name* and arguments *args*. # If *args* are Rubel statements, they will be evaluated beforehand. # This makes it possible to add objects and rubel statements to method calls. # # @return [Symbol] The name itself. This is useful for LOOKUPs. E.g. USER( test_123 ) # def method_missing(name, *args) if args.length > 0 Message.new(name, args) else name end end end end
class ImportRatefileProcess include Sidekiq::Worker include ImportHelper sidekiq_options queue: :import_ratefile_process, retry: 3 def perform(representative_number, representative_abbreviated_name, file_url = nil) Rate.delete_all RateDetailRecord.filter_by(representative_number).delete_all import_single_file(file_url || "https://s3.amazonaws.com/piarm/#{representative_abbreviated_name}/RATEFILE", 'rates', '~') end end
class Blog < ActiveRecord::Base validates :user_id, :title, :author, :content, :date_created, presence: true belongs_to :user has_many :blog_entries end
# -*- encoding : utf-8 -*- require File.dirname(__FILE__) + '/test_helper.rb' require 'modules/module_lmgtfy.rb' describe 'Module_Lmgtfy' do context "Lmgtfy module" do before(:each) do @bot = double() @module = Module_Lmgtfy.new @module.init_module(@bot) end it "reply to anonymous lmgtfy request" do expect(@bot).to receive(:send_privmsg).with("#channel", "http://lmgtfy.com/?q=some%20sentence") @module.privmsg(@bot, "someone", "#channel", "g some sentence") end it "reply to targeted lmgtfy request" do expect(@bot).to receive(:send_privmsg).with("#channel", "target: http://lmgtfy.com/?q=some%20sentence") @module.privmsg(@bot, "someone", "#channel", "target: g some sentence") end end end
require 'require_all' require_all './operations' require './text_builder/text_builder' def text_editor(instruction_text) text_state = TextBuilder.new instructions = InstructionParser.new instructions.load(instruction_text) instructions.instruction_lines.inject '' do |output, instruction_text| instruction = Instruction.new instruction.load_from_text(instruction_text) new_output = text_state.operate(instruction) if new_output && new_output.size > 0 append_to_output(output, new_output) else output end end end def append_to_output(output, new_output) if output.size > 0 output << "\n#{new_output}" return output elsif output == '' return new_output end end
class IdeaPolicy < ApplicationPolicy attr_reader :user, :idea def initialize(user, idea) @user = user @idea = idea end def update? user.admin? or idea.user == user end def destroy? user.admin? or idea.user == user end end
module Elasticsearch module Search class BaseClass include Elasticsearch::Search::Pagination def initialize(attrs={}) @params = attrs.fetch(:params) @sort_by = @params.fetch(:sort_by, '').to_sym @sort_order = @params.fetch(:sort_order, :asc).to_sym setup_pagination end def call return @result if @result @result = collection_class_name.__elasticsearch__.search(query).page(page).per(per_page) return @result unless @result.any? @result = @result.records end private attr_reader :params, :sort_by, :sort_order def collection_class_name raise 'No implementation' end def query_class_name raise 'No implementation' end def query query_class_name.new(params: params, sort_order: sort_order, sort_by: sort_by).call end end end end
require 'colorizr' class Game attr_reader :tribes def initialize(tribe1,tribe2) @tribes = [tribe1,tribe2] end def add_tribe(tribe) @tribes << tribe end def immunity_challenge losing_tribe = @tribes.sample puts "The losing tribe is " + losing_tribe.to_s.red losing_tribe end def clear_tribes @tribes.clear end def merge(tribe_name) all_members = @tribes[0].members + @tribes[1].members new_tribe=Tribe.new(name: tribe_name, members: all_members) clear_tribes add_tribe(new_tribe) new_tribe end def individual_immunity_challenge winner = @tribes.sample.members.sample puts "The winner is #{winner} and will not be eliminated." winner end end
require 'vizier/result-list' require 'Win32/Console/ANSI' if RUBY_PLATFORM =~ /win32/ require 'thread' module Kernel def puts(*args) $stdout.puts(*args) end end module Vizier class << self #Call anywhere to be sure that $stdout is replaced by an OutputStandin that #delegates to the original STDOUT IO. This by itself won't change output behavior. #Requiring 'vizier' does this for you. Multiple calls are safe though. def wrap_stdout return if $stdout.respond_to?(:add_dispatcher) $stdout = OutputStandin.new($stdout) end #If you need the actual IO for /dev/stdout, you can call this to get it. Useful inside of #Results::Formatter subclasses, for instance, so that they can actually send messages out to #the user. def raw_stdout if $stdout.respond_to?(:__getobj__) $stdout.__getobj__ else $stdout end end #See Vizier::wrap_stdout def wrap_stderr return if $stdout.respond_to?(:add_dispatcher) $stderr = OutputStandin.new($stderr) end #See Vizier::raw_stdout def raw_stderr if $stderr.respond_to?(:__getobj__) $stderr.__getobj__ else $stderr end end end #Wraps an IO using DelegateClass. Dispatches all calls to the IO, until a #Collector is registered, at which point, methods that the Collector #handles will get sent to it. class OutputStandin < IO def initialize(io) @_dc_obj = io unless io.fileno.nil? super(io.fileno,"w") end end def method_missing(m, *args) # :nodoc: unless @_dc_obj.respond_to?(m) super(m, *args) end @_dc_obj.__send__(m, *args) end def respond_to?(m) # :nodoc: return true if super return @_dc_obj.respond_to?(m) end def __getobj__ # :nodoc: @_dc_obj end def __setobj__(obj) # :nodoc: raise ArgumentError, "cannot delegate to self" if self.equal?(obj) @_dc_obj = obj end def clone # :nodoc: super __setobj__(__getobj__.clone) end def dup # :nodoc: super __setobj__(__getobj__.dup) end methods = IO.public_instance_methods(false) methods -= self.public_instance_methods(false) methods |= ['class'] methods.each do |method| begin module_eval <<-EOS def #{method}(*args, &block) begin @_dc_obj.__send__(:#{method}, *args, &block) rescue $@[0,2] = nil raise end end EOS rescue SyntaxError raise NameError, "invalid identifier %s" % method, caller(3) end end def thread_stack_index "standin_dispatch_stack_#{self.object_id}" end def relevant_collector Thread.current[thread_stack_index] || Thread.main[thread_stack_index] end def define_dispatch_methods(dispatcher)# :nodoc: dispatcher.dispatches.each do |dispatch| (class << self; self; end).module_eval <<-EOS def #{dispatch}(*args) dispatched_method(:#{dispatch.to_s}, *args) end EOS end end def dispatched_method(method, *args)# :nodoc: collector = relevant_collector if not collector.nil? and collector.respond_to?(method) return collector.__send__(method, *args) end return __getobj__.__send__(method, *args) end def add_thread_local_dispatcher(collector) Thread.current[thread_stack_index]=collector define_dispatch_methods(collector) end alias set_thread_collector add_thread_local_dispatcher alias add_dispatcher add_thread_local_dispatcher alias set_default_collector add_dispatcher #Unregisters the dispatcher. def remove_dispatcher(dispatcher) if Thread.current[thread_stack_index] == dispatcher Thread.current[thread_stack_index] = nil end end alias remove_collector remove_dispatcher alias remove_thread_local_dispatcher remove_dispatcher alias remove_thread_collector remove_thread_local_dispatcher end #This is the output management module for CommandSet. With an eye towards #being a general purpose UI library, and motivated by the need to manage #pretty serious output management, the Results module provides a #reasonably sophisticated output train that runs like this: # #0. An OutputStandin intercepts normal output and feeds it to ... #0. A Collector aggregates output from OutputStandins and explicit #item # and #list calls and feeds to to ... #0. A Presenter handles the stream of output from Collector objects and # emits +saw+ and +closed+ events to one or more ... #0. Formatter objects, which interpret those events into user-readable # output. module Results #Collects the events spawned by dispatchers and sends them to the presenter. #Responsible for maintaining it's own place within the larger tree, but doesn't #understand that other Collectors could be running at the same time - that's the #Presenter's job. class Collector def initialize(presenter, list_root) @presenter = presenter @nesting = [list_root] end def initialize_copy(original) @presenter = original.instance_variable_get("@presenter") @nesting = original.instance_variable_get("@nesting").dup end def items(*objs) if Hash === objs.last options = objs.pop else options = {} end objs.each do |obj| item(obj, options) end end def item( obj, options={} ) @presenter.item(@nesting.last, obj, options) end def begin_list( name, options={} ) @nesting << @presenter.begin_list(@nesting.last, name, options) if block_given? yield end_list end end def end_list @presenter.end_list(@nesting.pop) end @dispatches = {} def self.inherited(sub) sub.instance_variable_set("@dispatches", @dispatches.dup) end def self.dispatches @dispatches.keys end def dispatches self.class.dispatches end #Use to register an IO +method+ to handle. The block will be passed a #Collector and the arguments passed to +method+. def self.dispatch(method, &block) @dispatches[method] = true define_method(method, &block) end dispatch :puts do |*args| args.each do |arg| item arg end end dispatch :write do |*args| args.each do |arg| item arg end end dispatch :p do |*args| args.each do |arg| item(arg, :string => :inspect, :timing => :immediate) end end end #Gets item and list events from Collectors, and emits two kinds of #events to Formatters: #[+saw+ events] occur in chronological order, with no guarantee regarding timing. #[+closed+ events] occur in tree order. # #In general, +saw+ events are good for immediate feedback to the user, #not so good in terms of making sense of things. They're generated as #soon as the relevant output element enters the system. # #On the other hand, +closed+ events will be generated in the natural #order you'd expect the output to appear in. Most Formatter subclasses #use +closed+ events. # #A list which has not received a "list_end" event from upstream will #block lists later in tree order until it closes. A Formatter that #listens only to +closed+ events can present them to the user in a way #that should be reasonable, although output might be halting for any #process that takes noticeable time. # class Presenter class Exception < ::Exception; end def initialize @results = List.new("") @leading_edge = @results @formatters = [] @list_lock = Mutex.new end def create_collector return Collector.new(self, @results) end def register_formatter(formatter) @formatters << formatter formatter.notify(:start, nil) end def leading_edge?(list) return list == @leading_edge end def item( home, value, options={} ) item = ListItem.new(value) add_item(home, item, options) notify(:saw, item) return nil end def begin_list( home, name, options={} ) list = List.new(name) add_item(home, list, options) notify(:saw_begin, list) return list end def end_list( list ) @list_lock.synchronize do list.close advance_leading_edge end notify(:saw_end, list) return nil end def done @results.close advance_leading_edge notify(:done, nil) end #Returns the current list of results. A particularly advanced #Formatter might treat +saw_*+ events like notifications, and then use #the List#filter functionality to discover the specifics about the #item or list just closed. def output @results end protected def advance_leading_edge iter = ListIterator.new(@leading_edge.tree_order_next) iter.each do |forward| case forward when ListEnd break if forward.end_of.open? break if forward.end_of.name.empty? notify(:leave, forward.end_of) when List notify(:arrive, forward) when ListItem notify(:arrive, forward) end @leading_edge = forward end end def add_item(home, item, options) item.depth = home.depth + 1 @list_lock.synchronize do #home = get_collection(path) item.options = home.options.merge(options) home.add(item) advance_leading_edge end end def notify(msg, item) @formatters.each do |f| f.notify(msg, item) end end end end end
# rspec.info website describes the documentation to do this type of testing in ruby require 'minitest/autorun' class ChangeMachine # Returns an array indicating the quantity of # each denomination required. # [pennies, nickels, dimes, quarters] def issue_coins(amount_in_cents) end end describe ChangeMachine do it "should return one penny" do machine = ChangeMachine.new coins = machine.issue_coins(1) coins.must_equal [1,0,0,0] end # it "should return many pennies" do # machine = ChangeMachine.new # coins = machine.issue_coins(1) # coins.must_equal [4,0,0,0] # end end
require 'fs/xfs/inode' module XFS # //////////////////////////////////////////////////////////////////////////// # // Class. class InodeMap attr_reader :inode_blkno, :inode_length, :inode_boffset def valid_inode_size?(sb) if (@inode_blkno + @inode_length) > sb.fsb_to_bb(sb.block_count) $log.error "XFS::InodeMap - Inode #{@inode_blkno} too large for filesystem" if $log raise "XFS::InodeMap - Inode #{@inode_blkno} too large for filesystem" end true end def valid_inode_number?(inode, sb) if (@agno >= sb.sb['ag_count']) || (@agbno >= sb.sb['ag_blocks']) || sb.agino_to_ino(@agno, @agino) != inode $log.error "XFS::InodeMap - Bad Inode number #{inode} for agno #{@agno} agcount #{sb.sb['ag_count']}, agbno #{@agbno}, agblocks #{sb.sb['ag_blocks']}, agino #{@agino}, agino_to_ino #{sb.agino_to_ino(@agno, @agino)}" if $log raise "XFS::InodeMap - Bad Inode number #{inode}" end true end def initialize(inode, sb) # # Split up the inode number into its parts # @inode_number = inode @agno = sb.ino_to_agno(inode) @agino = sb.ino_to_agino(inode) @agbno = sb.agino_to_agbno(@agino) valid_inode_number?(inode, sb) || return # # If the inode cluster size is the same as the blocksize or # smaller we get to the block by simple arithmetic # blocks_per_cluster = sb.icluster_size_fsb @inode_length = sb.fsb_to_bb(blocks_per_cluster) if blocks_per_cluster == 1 offset = sb.ino_to_offset(inode) @inode_blkno = sb.agbno_to_real_block(@agno, @agbno) @inode_boffset = offset << sb['inode_size_log'] return elsif sb.inode_align_mask # # If the inode chunks are aligned then use simple math to # find the location. Otherwise we have to do a btree # lookup to find the location. # offset_agbno = @agbno & (sb.inode_align_mask - 1) chunk_agbno = @agbno - offset_agbno else start_ino = imap_lookup(@agno, @agino) chunk_agbno = sb.agino_to_agbno(start_ino) offset_agbno = @agbno - chunk_agbno end @cluster_agbno = chunk_agbno + (offset_agbno / blocks_per_cluster) * blocks_per_cluster offset = (@agbno - @cluster_agbno) * sb.sb['inodes_per_blk'] + sb.ino_to_offset(inode) @inode_blkno = sb.agbno_to_real_block(@agno, @cluster_agbno) @inode_boffset = offset << sb.sb['inode_size_log'] valid_inode_size?(sb) || return end # initialize def imap_lookup(agno, agino) ag = get_ag(agno) cursor = InodeBtreeCursor.new(@sb, ag.agi, agno, XFS_BTNUM_INO) cursor.block_ptr = ag.agblock error = inobt_lookup(cursor, agino, XFS_LOOKUP_LE) raise "XFS::Superblock.imap_lookup: #{error}" if error inode_rec = inode_btree_record(cursor) if inode_rec.nil? raise "XFS::Superblock.imap_lookup: Error #{cursor.error} getting InodeBtreeRecord for inode #{agino}" end if inode_rec.start_ino > agino || inode_rec.start_ino + @ialloc_inos <= agino raise "XFS::Superblock.imap_lookup: InodeBtreeRecord does not contain required inode #{agino}" end inode_rec.start_ino end # imap_lookup def dump out = "\#<#{self.class}:0x#{format('%08x', object_id)}>\n" out += "Inode Number : #{@inode_number}\n" out += "Alloc Grp Num: #{@agno}\n" out += "AG Ino : #{@agino}\n" out += "AG Block Num : #{@agbno}\n" out += "Inode Length : #{@inode_length}\n" out += "Inode Blkno : #{@inode_blkno}\n" out += "InoBlk Offset: #{@inode_boffset}\n" out += "Cluster AGBNO: #{@cluster_agbno}\n" out end end # Class InodeMap end # Module XFS
class CreateCourses < ActiveRecord::Migration def change create_table :courses do |t| t.string :business_name t.string :address t.string :city t.string :state t.string :zip t.string :phone t.string :course_type t.string :course_holes t.string :course_season t.string :course_dress_code t.timestamps null: false end end end
class Home::Categories::Products::Indices::DescriptionsController < ApplicationController # GET /home/categories/products/indices/descriptions # GET /home/categories/products/indices/descriptions.json def index @home_categories_products_indices_descriptions = Home::Categories::Products::Indices::Description.all respond_to do |format| format.html # index.html.erb format.json { render json: @home_categories_products_indices_descriptions } end end # GET /home/categories/products/indices/descriptions/1 # GET /home/categories/products/indices/descriptions/1.json def show @home_categories_products_indices_description = Home::Categories::Products::Indices::Description.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @home_categories_products_indices_description } end end # GET /home/categories/products/indices/descriptions/new # GET /home/categories/products/indices/descriptions/new.json def new @home_categories_products_indices_description = Home::Categories::Products::Indices::Description.new respond_to do |format| format.html # new.html.erb format.json { render json: @home_categories_products_indices_description } end end # GET /home/categories/products/indices/descriptions/1/edit def edit @home_categories_products_indices_description = Home::Categories::Products::Indices::Description.find(params[:id]) end # POST /home/categories/products/indices/descriptions # POST /home/categories/products/indices/descriptions.json def create @home_categories_products_indices_description = Home::Categories::Products::Indices::Description.new(params[:home_categories_products_indices_description]) respond_to do |format| if @home_categories_products_indices_description.save format.html { redirect_to @home_categories_products_indices_description, notice: 'Description was successfully created.' } format.json { render json: @home_categories_products_indices_description, status: :created, location: @home_categories_products_indices_description } else format.html { render action: "new" } format.json { render json: @home_categories_products_indices_description.errors, status: :unprocessable_entity } end end end # PUT /home/categories/products/indices/descriptions/1 # PUT /home/categories/products/indices/descriptions/1.json def update @home_categories_products_indices_description = Home::Categories::Products::Indices::Description.find(params[:id]) respond_to do |format| if @home_categories_products_indices_description.update_attributes(params[:home_categories_products_indices_description]) format.html { redirect_to @home_categories_products_indices_description, notice: 'Description was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @home_categories_products_indices_description.errors, status: :unprocessable_entity } end end end # DELETE /home/categories/products/indices/descriptions/1 # DELETE /home/categories/products/indices/descriptions/1.json def destroy @home_categories_products_indices_description = Home::Categories::Products::Indices::Description.find(params[:id]) @home_categories_products_indices_description.destroy respond_to do |format| format.html { redirect_to home_categories_products_indices_descriptions_url } format.json { head :no_content } end end end
class CarsController < ApplicationController def index @cars = Car.all.limit(10) end def new @car = Car.new end def create @car = Car.new(car_attr) if @car.save flash[:notice] = 'Success! Car added!' redirect_to cars_path else flash[:notice] = 'Sorry! The car could not be saved!' render :new end end private def car_attr params.require(:car).permit(:manufacturer_id, :color, :year, :mileage, :description) end end
class AddAsapToFavours < ActiveRecord::Migration[5.2] def change add_column :favours, :completion_asap, :binary end end
# == Schema Information # Schema version: 58 # # Table name: sds_jnlps # # id :integer(11) not null, primary key # portal_id :integer(11) # name :string(60) default(""), not null # url :string(256) # created_at :datetime # updated_at :datetime # body :text # always_update :boolean(1) # last_modified :datetime # filename :string(255) # require 'open-uri' class Jnlp < ActiveRecord::Base belongs_to :portal belongs_to :config_version has_many :offerings has_many :offerings, :order => "created_at DESC" before_validation :process_jnlp validates_presence_of :name, :url def validate unless body_xml errors.add("jnlp body: external resource: #{url} not well-formed xml.") end end def process_jnlp self.url.strip! get_body get_last_modified end # see: http://github.com/mislav/will_paginate/wikis/simple-search def self.search(search, page, portal) paginate :per_page => 20, :page => page, :conditions => ['name like ? and portal_id = ?',"%#{search}%", portal.id], :order => 'created_at DESC' end def get_body if self.always_update || self.body.blank? begin open(url) do |f| self.body = f.read self.last_modified = f.last_modified self.filename = File.basename(self.url) end rescue Exception => e if RAILS_ENV == 'production' additional_info = '' else additional_info = "\n#{e.message}\n\n#{e.backtrace.join("\n")}" end if self.body.length > 10 # use the old value of the jnlp for now else raise "There was a problem saving the jnlp to the filesystem\n#{additional_info}" end end end self.body end def get_last_modified if self.always_update || self.body.blank? uri = URI.parse(url) begin Net::HTTP.start(uri.host, uri.port) do |http| head = Net::HTTP.start(uri.host, uri.port) {|http| http.head(uri.path, 'User-Agent' => '')} if head.class == Net::HTTPOK self.last_modified=Time::httpdate(head['Last-Modified']) else 'jnlp not available' end end rescue SocketError "network unavailable" rescue Timeout::Error "network timeout" rescue Exception "exception" end end end def body_xml if USE_LIBXML begin XML::Parser.string(self.body).parse.root rescue XML::Parser::ParseError nil end else require "rexml/document" REXML::Document.new(self.body).root end end # Jnlp.find(:all).each {|j| print "#{j.id}: "; begin j.save! rescue print "error, " ensure puts "#{j.name}" end }; nil # 4: error: basic-emf-post # 5: error: basic-emf # 6: error: pedagogica-emf # 7: error: pedagogica-emf-snapshot # 9: error: pedagogica-emf end
class EricWeixin::Report::NewsData < ActiveRecord::Base self.table_name = 'weixin_report_news_data' NEWS_DATA_TYPE = ['summary', 'total', 'read', 'read_hour', 'share', 'share_hour'] SHARE_SCENE = { 1 => '好友转发', 2 => '朋友圈', 3 => '腾讯微博', 255 => '其他' } validates_presence_of :news_data_type, message: "数据类型不可以为空。" validates_inclusion_of :news_data_type, in: NEWS_DATA_TYPE, message: "不正确的数据类型,只能为summary、total、read、read_hour、share、share_hour其中一个。" # 自动去微信服务器拉取当日前一天的统计模块的图文数据. # ===参数说明 # * weixin_public_account_id # 微信公众号ID # ===调用实例 # ::EricWeixin::Report::NewsData.auto_execute_get_and_save_data_from_weixin 1 def self.auto_execute_get_and_save_data_from_weixin weixin_public_account_id self.transaction do yesterday = (Time.now - 1.day).to_date.to_s # 取当天的前一天数据 get_and_save_data_from_weixin yesterday, yesterday, weixin_public_account_id get_and_save_article_total yesterday, yesterday, weixin_public_account_id get_and_save_user_read_hour yesterday, yesterday, weixin_public_account_id get_and_save_user_share_hour yesterday, yesterday, weixin_public_account_id get_and_save_user_share yesterday, yesterday, weixin_public_account_id get_and_save_user_read yesterday, yesterday, weixin_public_account_id end end # 创建一个微信图文数据news_data. # ===参数说明 # * ref_date # 数据的日期 # * ref_hour # 数据的小时,包括从000到2300,分别代表的是[000,100)到[2300,2400),即每日的第1小时和最后1小时 # * stat_date # 统计的日期,在getarticletotal接口中,ref_date指的是文章群发出日期, 而stat_date是数据统计日期 # * msgid # 这里的msgid实际上是由msgid(图文消息id)和index(消息次序索引)组成, 例如12003_3, 其中12003是msgid,即一次群发的id消息的; 3为index,假设该次群发的图文消息共5个文章(因为可能为多图文), 3表示5个中的第3个 # * title # 图文消息的标题 # * int_page_read_user # 图文页(点击群发图文卡片进入的页面)的阅读人数 # * int_page_read_count # 图文页的阅读次数 # * ori_page_read_user # 原文页(点击图文页“阅读原文”进入的页面)的阅读人数,无原文页时此处数据为0 # * ori_page_read_count # 原文页的阅读次数 # * share_scene # 分享的场景 1代表好友转发 2代表朋友圈 3代表腾讯微博 255代表其他 # * share_user # 分享的人数 # * share_count # 分享的次数 # * add_to_fav_user # 收藏的人数 # * add_to_fav_count # 收藏的次数 # * target_user # 送达人数,一般约等于总粉丝数(需排除黑名单或其他异常情况下无法收到消息的粉丝) # * weixin_public_account_id # 公众号ID # * news_data_type # 数据类型,包括summary、total、read、read_hour、share、share_hour # * user_source # 数据来源 # * total_online_time # 总在线时间 # ===调用实例 # options = {ref_date: '2015-6-6', ref_hour: 0, weixin_public_account_id: 1, news_data_type: 'summary' ... } # ::EricWeixin::Report::NewsData.create_news_data options def self.create_news_data options self.transaction do options = get_arguments_options options, [:ref_date, :ref_hour, :stat_date, :msgid, :title, :int_page_read_user, :int_page_read_count, :ori_page_read_user, :ori_page_read_count, :share_scene, :share_user, :share_count, :add_to_fav_user, :add_to_fav_count, :target_user, :weixin_public_account_id, :news_data_type, :user_source, :total_online_time] news_data = self.new options news_data.save! news_data.reload news_data end end # 通过参数确定是否存在这样一个微信图文数据news_data. # ===参数说明 # * ref_date # 数据的日期 # * ref_hour # 数据的小时,包括从000到2300,分别代表的是[000,100)到[2300,2400),即每日的第1小时和最后1小时 # * stat_date # 统计的日期,在getarticletotal接口中,ref_date指的是文章群发出日期, 而stat_date是数据统计日期 # * msgid # 这里的msgid实际上是由msgid(图文消息id)和index(消息次序索引)组成, 例如12003_3, 其中12003是msgid,即一次群发的id消息的; 3为index,假设该次群发的图文消息共5个文章(因为可能为多图文), 3表示5个中的第3个 # * title # 图文消息的标题 # * int_page_read_user # 图文页(点击群发图文卡片进入的页面)的阅读人数 # * int_page_read_count # 图文页的阅读次数 # * ori_page_read_user # 原文页(点击图文页“阅读原文”进入的页面)的阅读人数,无原文页时此处数据为0 # * ori_page_read_count # 原文页的阅读次数 # * share_scene # 分享的场景 1代表好友转发 2代表朋友圈 3代表腾讯微博 255代表其他 # * share_user # 分享的人数 # * share_count # 分享的次数 # * add_to_fav_user # 收藏的人数 # * add_to_fav_count # 收藏的次数 # * target_user # 送达人数,一般约等于总粉丝数(需排除黑名单或其他异常情况下无法收到消息的粉丝) # * weixin_public_account_id # 公众号ID # * news_data_type # 数据类型,包括summary、total、read、read_hour、share、share_hour # * user_source # 数据来源 # * total_online_time # 总在线时间 # ===调用实例 # options = {ref_date: '2015-6-6', ref_hour: 0, weixin_public_account_id: 1, news_data_type: 'summary' ... } # ::EricWeixin::Report::NewsData.exist options # ===返回 # true 代表存在 # false 代表不存在 def self.exist options options = get_arguments_options options, [:ref_date, :ref_hour, :stat_date, :msgid, :title, :int_page_read_user, :int_page_read_count, :ori_page_read_user, :ori_page_read_count, :share_scene, :share_user, :share_count, :add_to_fav_user, :add_to_fav_count, :target_user, :weixin_public_account_id, :news_data_type, :user_source, :total_online_time] self.where( options ).count >= 1 end # 获得公众平台官网数据统计模块中图文群发每日数据&保存到数据库. # ===参数说明 # * begin_date # 获取数据的起始日期,begin_date和end_date的差值需小于1 # * end_date # 获取数据的结束日期,end_date允许设置的最大值为昨日 # * weixin_public_account_id # 公众号ID # ===调用实例 # ::EricWeixin::Report::NewsData.get_and_save_data_from_weixin '2015-6-1', '2015-6-1', 1 def self.get_and_save_data_from_weixin begin_date, end_date, weixin_public_account_id self.transaction do options = { :begin_date => begin_date, :end_date => end_date, :weixin_public_account_id => weixin_public_account_id } # get_article_summary article_summary = ::EricWeixin::AnalyzeData.get_article_summary options pp "############################ article_summary ####################################" pp article_summary list_summary = article_summary["list"] list_summary.each do |s| s = s.merge(news_data_type: 'summary').merge(weixin_public_account_id: weixin_public_account_id) self.create_news_data s unless self.exist s end unless list_summary.blank? end end # 获得公众平台官网数据统计模块中图文群发总数据&保存到数据库. # ===参数说明 # * begin_date # 获取数据的起始日期,begin_date和end_date的差值需小于1 # * end_date # 获取数据的结束日期,end_date允许设置的最大值为昨日 # * weixin_public_account_id # 公众号ID # ===调用实例 # ::EricWeixin::Report::NewsData.get_and_save_article_total '2015-6-1', '2015-6-1', 1 def self.get_and_save_article_total begin_date, end_date, weixin_public_account_id self.transaction do options = { :begin_date => begin_date, :end_date => end_date, :weixin_public_account_id => weixin_public_account_id } # get_article_total article_total = ::EricWeixin::AnalyzeData.get_article_total options pp "############################ article_total ####################################" pp article_total list_total = article_total["list"] list_total.each do |s| s = s.merge(news_data_type: 'total').merge(weixin_public_account_id: weixin_public_account_id) details = s["details"] details.each do |d| self.create_news_data s.merge(d) unless self.exist s.merge(d) end unless details.blank? end unless list_total.blank? end end # 获得公众平台官网数据统计模块中图文统计数据&保存到数据库. # ===参数说明 # * begin_date # 获取数据的起始日期,begin_date和end_date的差值需小于3 # * end_date # 获取数据的结束日期,end_date允许设置的最大值为昨日 # * weixin_public_account_id # 公众号ID # ===调用实例 # ::EricWeixin::Report::NewsData.get_and_save_user_read '2015-6-1', '2015-6-3', 1 def self.get_and_save_user_read begin_date, end_date, weixin_public_account_id self.transaction do options = { :begin_date => begin_date, :end_date => end_date, :weixin_public_account_id => weixin_public_account_id } # get_user_read user_read = ::EricWeixin::AnalyzeData.get_user_read options pp "############################ user_read ####################################" pp user_read list_read = user_read["list"] list_read.each do |s| s = s.merge(news_data_type: 'read').merge(weixin_public_account_id: weixin_public_account_id) self.create_news_data s unless self.exist s end unless list_read.blank? end end # 获得公众平台官网数据统计模块中图文统计分时数据&保存到数据库. # ===参数说明 # * begin_date # 获取数据的起始日期,begin_date和end_date的差值需小于1 # * end_date # 获取数据的结束日期,end_date允许设置的最大值为昨日 # * weixin_public_account_id # 公众号ID # ===调用实例 # ::EricWeixin::Report::NewsData.get_and_save_user_read_hour '2015-6-1', '2015-6-1', 1 def self.get_and_save_user_read_hour begin_date, end_date, weixin_public_account_id self.transaction do options = { :begin_date => begin_date, :end_date => end_date, :weixin_public_account_id => weixin_public_account_id } # get_user_read_hour user_read_hour = ::EricWeixin::AnalyzeData.get_user_read_hour options pp "############################ user_read_hour ####################################" pp user_read_hour list_read_hour = user_read_hour["list"] list_read_hour.each do |s| s = s.merge(news_data_type: 'read_hour').merge(weixin_public_account_id: weixin_public_account_id) self.create_news_data s unless self.exist s end unless list_read_hour.blank? end end # 获得公众平台官网数据统计模块中图文分享转发数据&保存到数据库. # ===参数说明 # * begin_date # 获取数据的起始日期,begin_date和end_date的差值需小于7 # * end_date # 获取数据的结束日期,end_date允许设置的最大值为昨日 # * weixin_public_account_id # 公众号ID # ===调用实例 # ::EricWeixin::Report::NewsData.get_and_save_user_share '2015-6-1', '2015-6-7', 1 def self.get_and_save_user_share begin_date, end_date, weixin_public_account_id self.transaction do options = { :begin_date => begin_date, :end_date => end_date, :weixin_public_account_id => weixin_public_account_id } # get_user_share user_share = ::EricWeixin::AnalyzeData.get_user_share options pp "############################ user_share ####################################" pp user_share list_share = user_share["list"] list_share.each do |s| s = s.merge(news_data_type: 'share').merge(weixin_public_account_id: weixin_public_account_id) self.create_news_data s unless self.exist s end unless list_share.blank? end end # 获得公众平台官网数据统计模块中图文分享转发分时数据&保存到数据库. # ===参数说明 # * begin_date # 获取数据的起始日期,begin_date和end_date的差值需小于1 # * end_date # 获取数据的结束日期,end_date允许设置的最大值为昨日 # * weixin_public_account_id # 公众号ID # ===调用实例 # ::EricWeixin::Report::NewsData.get_and_save_user_share_hour '2015-6-1', '2015-6-1', 1 def self.get_and_save_user_share_hour begin_date, end_date, weixin_public_account_id self.transaction do options = { :begin_date => begin_date, :end_date => end_date, :weixin_public_account_id => weixin_public_account_id } # get_user_share_hour user_share_hour = ::EricWeixin::AnalyzeData.get_user_share_hour options pp "############################ user_share_hour ####################################" pp user_share_hour list_share_hour = user_share_hour["list"] list_share_hour.each do |s| s = s.merge(news_data_type: 'share_hour').merge(weixin_public_account_id: weixin_public_account_id) self.create_news_data s unless self.exist s end unless list_share_hour.blank? end end end
# encoding: UTF-8 require 'spec_helper' describe Folio do subject { Fabricate(:folio) } it { should ensure_inclusion_of(:state).in_array(Folio::STATES) } end
namespace :db do desc "Fill database with data" task populate: :environment do make_users make_hotels make_ratings make_admin end end def make_admin email = "admin@hotels.org" password = "password" Admin.create!(email: email, password: password, password_confirmation: password) end def make_users 10.times do |n| username = "user-#{n+1}" email = "user-#{n+1}@hotels.org" password = "password" User.create!(username: username,email: email, password: password, password_confirmation: password) end end def make_hotels users = User.all users.each { |user| title = Faker::Company.name breakfast = [true, false].sample price_for_room = rand(1000) / (rand(100) + 1) country = Faker::Address.country state = Faker::Address.state city = Faker::Address.city street = Faker::Address.street_name room_description = Faker::Lorem.paragraph name_of_photo = File.open(File.join(Rails.root,"app/uploaders/#{user.id}.jpeg")) user.hotels.create!(title: title, breakfast: breakfast, price_for_room: price_for_room, country: country,state: state,city: city,street: street, room_description: room_description, name_of_photo: name_of_photo) } end def make_ratings users = User.all hotels = Hotel.all ratings = Rating.all hotels.each {|hotel| users.each {|user| value=rand(5) comment = Faker::Lorem.sentence if (user.id==hotel.user_id) else ratings.create!(user_id: user.id, hotel_id: hotel.id, value: value, comment: comment) end } } end
require 'rails_helper' RSpec.feature 'New zone in admin area', settings: false do background do sign_in_to_admin_area end scenario 'it creates new zone' do open_list open_form fill_form submit_form expect(page).to have_text(t('admin.dns.zones.create.created')) end def open_list click_link_or_button t('admin.base.menu.zones') end def open_form click_link_or_button t('admin.dns.zones.index.new_btn') end def fill_form fill_in 'zone_origin', with: 'test' fill_in 'zone_ttl', with: '1' fill_in 'zone_refresh', with: '1' fill_in 'zone_retry', with: '1' fill_in 'zone_expire', with: '1' fill_in 'zone_minimum_ttl', with: '1' fill_in 'zone_email', with: 'test@test.com' fill_in 'zone_master_nameserver', with: 'test.test' end def submit_form click_link_or_button t('admin.dns.zones.form.create_btn') end end
RSpec.shared_context "yammer PUT" do |endpoint| let(:request_url) { "https://www.yammer.com/api/v1/#{endpoint}" } let!(:mock) { stub_request(:put, request_url).with( headers: { 'Authorization' => 'Bearer shakenn0tst1rr3d' } ). to_return(status: 201, body: "{}", headers: {}) } end
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- # stub: permutation-tools 0.2.3 ruby lib Gem::Specification.new do |s| s.name = "permutation-tools" s.version = "0.2.3" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.require_paths = ["lib"] s.authors = ["Ian Hunter"] s.date = "2015-08-24" s.description = "" s.email = "ianhunter@gmail.com" s.executables = ["permutation"] s.extra_rdoc_files = [ "LICENSE.txt", "README.md" ] s.files = [ "Gemfile", "Gemfile.lock", "LICENSE.txt", "README.md", "Rakefile", "VERSION", "bin/permutation", "index.html", "lib/ext/hash.rb", "lib/ext/scraper.rb", "lib/permutation-tools.rb", "lib/tools/api.rb", "lib/tools/config.rb", "lib/tools/mirror.rb", "lib/tools/release.rb", "lib/tools/server.rb", "permutation-tools.gemspec", "test/helper.rb", "test/test_permutation-tools.rb" ] s.homepage = "http://github.com/ihunter/permutation-tools" s.licenses = ["MIT"] s.rubygems_version = "2.4.6" s.summary = "Tools for working with Permutation" if s.respond_to? :specification_version then s.specification_version = 4 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_runtime_dependency(%q<faraday>, [">= 0"]) s.add_runtime_dependency(%q<highline>, [">= 0"]) s.add_runtime_dependency(%q<json>, [">= 0"]) s.add_runtime_dependency(%q<semantic>, [">= 0"]) s.add_runtime_dependency(%q<sinatra>, [">= 0"]) s.add_development_dependency(%q<byebug>, [">= 0"]) s.add_development_dependency(%q<shoulda>, [">= 0"]) s.add_development_dependency(%q<rdoc>, ["~> 3.12"]) s.add_development_dependency(%q<bundler>, ["~> 1.0"]) s.add_development_dependency(%q<jeweler>, ["~> 2.0.1"]) s.add_development_dependency(%q<simplecov>, [">= 0"]) else s.add_dependency(%q<faraday>, [">= 0"]) s.add_dependency(%q<highline>, [">= 0"]) s.add_dependency(%q<json>, [">= 0"]) s.add_dependency(%q<semantic>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) s.add_dependency(%q<byebug>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 2.0.1"]) s.add_dependency(%q<simplecov>, [">= 0"]) end else s.add_dependency(%q<faraday>, [">= 0"]) s.add_dependency(%q<highline>, [">= 0"]) s.add_dependency(%q<json>, [">= 0"]) s.add_dependency(%q<semantic>, [">= 0"]) s.add_dependency(%q<sinatra>, [">= 0"]) s.add_dependency(%q<byebug>, [">= 0"]) s.add_dependency(%q<shoulda>, [">= 0"]) s.add_dependency(%q<rdoc>, ["~> 3.12"]) s.add_dependency(%q<bundler>, ["~> 1.0"]) s.add_dependency(%q<jeweler>, ["~> 2.0.1"]) s.add_dependency(%q<simplecov>, [">= 0"]) end end
class Picture < ActiveRecord::Base belongs_to :user validates :user_id, presence: true mount_uploader :link, PictureUploader has_many :comments, dependent: :destroy def next user.pictures.where("id > ?", id).first end def prev user.pictures.where("id < ?", id).last end end
module StringExtensions class String def contains_lowercase_letters return self.match('/[a-z]/'); end def contains_uppercase_letters return self.match('/[A-Z]/'); end def contains_digits return self.match('/\d/'); end end end
require 'yt/collections/base' module Yt module Collections # @private class Reports < Base DIMENSIONS = Hash.new({name: 'day', parse: ->(day, *values) { @metrics.keys.zip(values.map{|v| {Date.iso8601(day) => v}}).to_h} }).tap do |hash| hash[:month] = {name: 'month', parse: ->(month, *values) { @metrics.keys.zip(values.map{|v| {Range.new(Date.strptime(month, '%Y-%m').beginning_of_month, Date.strptime(month, '%Y-%m').end_of_month) => v} }).to_h} } hash[:week] = {name: '7DayTotals', parse: ->(last_day_of_week, *values) { @metrics.keys.zip(values.map{|v| {Range.new(Date.strptime(last_day_of_week) - 6, Date.strptime(last_day_of_week)) => v} }).to_h} } hash[:range] = {parse: ->(*values) { @metrics.keys.zip(values.map{|v| {total: v}}).to_h } } hash[:traffic_source] = {name: 'insightTrafficSourceType', parse: ->(source, *values) { @metrics.keys.zip(values.map{|v| {TRAFFIC_SOURCES.key(source) => v}}).to_h} } hash[:playback_location] = {name: 'insightPlaybackLocationType', parse: ->(location, *values) { @metrics.keys.zip(values.map{|v| {PLAYBACK_LOCATIONS.key(location) => v}}).to_h} } hash[:embedded_player_location] = {name: 'insightPlaybackLocationDetail', parse: ->(url, *values) {@metrics.keys.zip(values.map{|v| {url => v}}).to_h} } hash[:subscribed_status] = {name: 'subscribedStatus', parse: ->(status, *values) {@metrics.keys.zip(values.map{|v| {SUBSCRIBED_STATUSES.key(status) => v}}).to_h} } hash[:related_video] = {name: 'insightTrafficSourceDetail', parse: ->(video_id, *values) { @metrics.keys.zip(values.map{|v| {video_id => v}}).to_h} } hash[:search_term] = {name: 'insightTrafficSourceDetail', parse: ->(search_term, *values) {@metrics.keys.zip(values.map{|v| {search_term => v}}).to_h} } hash[:referrer] = {name: 'insightTrafficSourceDetail', parse: ->(url, *values) {@metrics.keys.zip(values.map{|v| {url => v}}).to_h} } hash[:video] = {name: 'video', parse: ->(video_id, *values) { @metrics.keys.zip(values.map{|v| {video_id => v}}).to_h} } hash[:playlist] = {name: 'playlist', parse: ->(playlist_id, *values) { @metrics.keys.zip(values.map{|v| {playlist_id => v}}).to_h} } hash[:device_type] = {name: 'deviceType', parse: ->(type, *values) {@metrics.keys.zip(values.map{|v| {DEVICE_TYPES.key(type) => v}}).to_h} } hash[:operating_system] = {name: 'operatingSystem', parse: ->(os, *values) {@metrics.keys.zip(values.map{|v| {OPERATING_SYSTEMS.key(os) => v}}).to_h} } hash[:country] = {name: 'country', parse: ->(country_code, *values) { @metrics.keys.zip(values.map{|v| {country_code => v}}).to_h} } hash[:state] = {name: 'province', parse: ->(country_and_state_code, *values) { @metrics.keys.zip(values.map{|v| {country_and_state_code[3..-1] => v}}).to_h} } hash[:gender_age_group] = {name: 'gender,ageGroup', parse: ->(gender, *values) { [gender.downcase.to_sym, *values] }} hash[:gender] = {name: 'gender', parse: ->(gender, *values) {@metrics.keys.zip(values.map{|v| {gender.downcase.to_sym => v}}).to_h} } hash[:age_group] = {name: 'ageGroup', parse: ->(age_group, *values) {@metrics.keys.zip(values.map{|v| {age_group[3..-1] => v}}).to_h} } end # @see https://developers.google.com/youtube/analytics/v1/dimsmets/dims#Traffic_Source_Dimensions # @note EXT_APP is also returned but it’s not in the documentation above! TRAFFIC_SOURCES = { advertising: 'ADVERTISING', annotation: 'ANNOTATION', external_app: 'EXT_APP', external_url: 'EXT_URL', embedded: 'NO_LINK_EMBEDDED', other: 'NO_LINK_OTHER', playlist: 'PLAYLIST', promoted: 'PROMOTED', related_video: 'RELATED_VIDEO', subscriber: 'SUBSCRIBER', channel: 'YT_CHANNEL', other_page: 'YT_OTHER_PAGE', search: 'YT_SEARCH', google: 'GOOGLE_SEARCH', notification: 'NOTIFICATION', playlist_page: 'YT_PLAYLIST_PAGE', campaign_card: 'CAMPAIGN_CARD', end_screen: 'END_SCREEN', info_card: 'INFO_CARD' } # @see https://developers.google.com/youtube/analytics/v1/dimsmets/dims#Playback_Location_Dimensions PLAYBACK_LOCATIONS = { channel: 'CHANNEL', watch: 'WATCH', embedded: 'EMBEDDED', other: 'YT_OTHER', external_app: 'EXTERNAL_APP', search: 'SEARCH', # undocumented but returned by the API browse: 'BROWSE', # undocumented but returned by the API mobile: 'MOBILE' # only present for data < September 10, 2013 } # @see https://developers.google.com/youtube/analytics/v1/dimsmets/dims#Playback_Detail_Dimensions SUBSCRIBED_STATUSES = { subscribed: 'SUBSCRIBED', unsubscribed: 'UNSUBSCRIBED' } # @see https://developers.google.com/youtube/analytics/v1/dimsmets/dims#Device_Dimensions DEVICE_TYPES = { desktop: 'DESKTOP', game_console: 'GAME_CONSOLE', mobile: 'MOBILE', tablet: 'TABLET', tv: 'TV', unknown_platform: 'UNKNOWN_PLATFORM' } # @see https://developers.google.com/youtube/analytics/v1/dimsmets/dims#Device_Dimensions OPERATING_SYSTEMS = { android: 'ANDROID', bada: 'BADA', blackberry: 'BLACKBERRY', chromecast: 'CHROMECAST', docomo: 'DOCOMO', hiptop: 'HIPTOP', ios: 'IOS', linux: 'LINUX', macintosh: 'MACINTOSH', meego: 'MEEGO', nintendo_3ds: 'NINTENDO_3DS', other: 'OTHER', playstation: 'PLAYSTATION', playstation_vita: 'PLAYSTATION_VITA', smart_tv: 'SMART_TV', symbian: 'SYMBIAN', webos: 'WEBOS', wii: 'WII', windows: 'WINDOWS', windows_mobile: 'WINDOWS_MOBILE', xbox: 'XBOX' } attr_writer :metrics def within(days_range, country, state, dimension, videos, try_again = true) @days_range = days_range @dimension = dimension @country = country @state = state @videos = videos if dimension == :gender_age_group # array of array Hash.new{|h,k| h[k] = Hash.new 0.0}.tap do |hash| each{|gender, age_group, value| hash[gender][age_group[3..-1]] = value} end else hash = flat_map do |hashes| hashes.map do |metric, values| [metric, values.inject({}){|h,(k,v)| h[k] = type_cast(v, @metrics[metric]); h}] end.to_h end hash = hash.inject(@metrics.inject({}){|h,(k,v)| h[k] = {}; h}) do |result, hash| result.deep_merge hash end if dimension == :month hash = hash.inject({}){|h,(k,v)| h[k] = v.sort_by{|range, v| range.first}.to_h; h} elsif dimension == :week hash = hash.inject({}) do |h,(k,v)| h[k] = v.select{|range, v| range.last.wday == days_range.last.wday}. sort_by{|range, v| range.first }.to_h h end elsif dimension == :day hash = hash.inject({}){|h,(k,v)| h[k] = v.sort_by{|day, v| day}.to_h; h} elsif [:traffic_source, :country, :state, :playback_location, :device_type, :operating_system, :subscribed_status].include?(dimension) hash = hash.inject({}){|h,(k,v)| h[k] = v.sort_by{|range, v| -v}.to_h; h} end (@metrics.one? || @metrics.keys == [:estimated_revenue, :estimated_minutes_watched]) ? hash[@metrics.keys.first] : hash end # NOTE: Once in a while, YouTube responds with 400 Error and the message # "Invalid query. Query did not conform to the expectations."; in this # case running the same query after one second fixes the issue. This is # not documented by YouTube and hardly testable, but trying again the # same query is a workaround that works and can hardly cause any damage. # Similarly, once in while YouTube responds with a random 503 error. rescue Yt::Error => e try_again && rescue?(e) ? sleep(3) && within(days_range, country, state, dimension, videos, false) : raise end private def type_cast(value, type) case [type] when [Integer] then value.to_i if value when [Float] then value.to_f if value end end def new_item(data) instance_exec *data, &DIMENSIONS[@dimension][:parse] end # @see https://developers.google.com/youtube/analytics/v1/content_owner_reports def list_params super.tap do |params| params[:path] = '/youtube/analytics/v1/reports' params[:params] = reports_params params[:camelize_params] = false end end def reports_params @parent.reports_params.tap do |params| params['start-date'] = @days_range.begin params['end-date'] = @days_range.end params['metrics'] = @metrics.keys.join(',').to_s.camelize(:lower) params['dimensions'] = DIMENSIONS[@dimension][:name] unless @dimension == :range params['max-results'] = 50 if [:playlist, :video].include?(@dimension) params['max-results'] = 25 if [:embedded_player_location, :related_video, :search_term, :referrer].include?(@dimension) if [:video, :playlist, :embedded_player_location, :related_video, :search_term, :referrer].include?(@dimension) if @metrics.keys == [:estimated_revenue, :estimated_minutes_watched] params['sort'] = '-estimatedRevenue' else params['sort'] = "-#{@metrics.keys.join(',').to_s.camelize(:lower)}" end end params[:filters] = "video==#{@videos.join ','}" if @videos params[:filters] = ((params[:filters] || '').split(';') + ["country==US"]).compact.uniq.join(';') if @dimension == :state && !@state params[:filters] = ((params[:filters] || '').split(';') + ["country==#{@country}"]).compact.uniq.join(';') if @country && !@state params[:filters] = ((params[:filters] || '').split(';') + ["province==US-#{@state}"]).compact.uniq.join(';') if @state params[:filters] = ((params[:filters] || '').split(';') + ['isCurated==1']).compact.uniq.join(';') if @dimension == :playlist params[:filters] = ((params[:filters] || '').split(';') + ['insightPlaybackLocationType==EMBEDDED']).compact.uniq.join(';') if @dimension == :embedded_player_location params[:filters] = ((params[:filters] || '').split(';') + ['insightTrafficSourceType==RELATED_VIDEO']).compact.uniq.join(';') if @dimension == :related_video params[:filters] = ((params[:filters] || '').split(';') + ['insightTrafficSourceType==YT_SEARCH']).compact.uniq.join(';') if @dimension == :search_term params[:filters] = ((params[:filters] || '').split(';') + ['insightTrafficSourceType==EXT_URL']).compact.uniq.join(';') if @dimension == :referrer end end def items_key 'rows' end def rescue?(error) error.reasons.include?('badRequest') && error.to_s =~ /did not conform/ end end end end
def source 'protocol MyAwesomeProtocol:Foo{}' end def expected_tokens [ T_PROTOCOL, T_WHITESPACES(' '), T_IDENTIFIER('MyAwesomeProtocol'), T_COLON, T_IDENTIFIER('Foo'), T_OPEN_CURLY_BRACKET, T_CLOSE_CURLY_BRACKET ] end def expected_ast { __type: 'program', body: [ { __type: 'protocol-declaration', name: { __type: 'identifier', value: 'MyAwesomeProtocol' }, inheritances: [ { __type: 'identifier', value: 'Foo' } ], declarations: [] } ] } end load 'spec_builder.rb'
module ApplicationHelper # Help build gumby forms def page_path(page, include_site=true) site_path = page.site.path path_elems = [page.slug.to_s] while !page.parent.nil? page = page.parent path_elems << page.slug.to_s end if include_site && page.site.render_site_path File.join('/', site_path, path_elems.reverse.compact) else File.join('/', path_elems.reverse.compact).gsub('//','/') end end # path to static assets for cms site def cms_site_asset_path(relpath='', site_handle='') File.join('/', site_handle, relpath.sub(/^\/+/,'')) end # url to static assets for cms site def cms_site_asset_url(relpath='', site_handle) url_prefix = request.original_url[/^\w+:\/+[^\/]+/] File.join(url_prefix, cms_site_asset_path(relpath, site_handle).sub(/^\/+/,'')) end # this is a helper to retrieve related page's content in layouts/snippets def page_content_for(slug, identifier) page = @cms_site.pages.find_by_slug(identifier.to_s) return '' if page.nil? block = page.blocks.find_by_identifier(identifier) return '' if block.nil? return block.inspect case block.tag # This just handles very simple text content atm when ComfortableMexicanSofa::Tag::PageFile '' when ComfortableMexicanSofa::Tag::PageFiles '' else ComfortableMexicanSofa::Tag.sanitize_irb(block.content) end end # returns an array of page objects or properies of pages of hierarchical relationships def breadcrumbs(page, method=nil) crumbs = [] while !page.nil? crumbs << (method ? page.send(method) : page) page = page.parent return (crumbs << page.site.pages.root) if !page.nil? && page.is_leaf_node # don't add leaf_node parents to breadcrumbs end crumbs end # checkbox with label included, Gumby-style def gumby_checkbox(form_builder, method, label, checked=false, value="1") name = "#{form_builder.object.class.name.underscore}[#{method}]" checkbox = check_box_tag(name, value, checked) + content_tag(:span) + ' ' + label.to_s html = label_tag(name, checkbox, :class => "checkbox#{checked ? ' checked' : ''}") html + hidden_field_tag(name, (value.to_i == 0) ? '1' : '0', :id => nil) end # a form field that displays an image, or an upload file field alternatively def cms_image_or_upload_field(form_builder, method) klass = form_builder.object.class.name.sub('Cms::','') name = "#{klass.underscore}[#{method}]" file_display = !form_builder.object.send(method).path.blank? file_input = content_tag(:div, content_tag(:div, file_field_tag(name)), class: 'controls', style: (file_display ? 'display: none;' : '')) image = content_tag(:div, image_tag(form_builder.object.send(method).url, onclick: "$('##{name.gsub(/[\[\]]/,'_').sub(/_$/,'').underscore}').parent().parent().show();$(this).hide();"), style: file_display ? '' : 'display: none;') content_tag(:div, (label_tag(name, t(".#{method}"), :class => 'control-label').concat(image).concat(file_input)), class: 'control-group') end def fancytree_pages_hash(pages, branch_id=nil, &labelling) item_model = pages[branch_id].first.class.name.underscore.split('/').last unless pages[branch_id].empty? labelling = ->(item) { fancytree_label_for(item) } unless block_given? pages[branch_id].map do |page| child_pages = pages[page.id] || [] page_hash = { title: labelling.call(page), key: page.id, href: method("edit_admin_cms_site_#{item_model}_path".sub('site_site','site')).call({site_id: (@site.nil? ? nil : @site.id), id: page.id, format: :js}) } unless child_pages.empty? page_hash.merge!({ folder: true, children: fancytree_pages_hash(pages, page.id, &labelling)}) end page_hash end end def fancytree_grouped_hash(groups, items, branch_id=nil, top_node=true, new_link=true, lazy=true, &labelling) # use the containing group to determine model type if this is empty model_group = groups[branch_id] model_group ||= groups[groups.select{|k,g| g.include?(branch_id)}.keys.first] item_model = (model_group || groups).first.grouped_type.underscore.split('/').last labelling = ->(item) { fancytree_label_for(item) } unless block_given? collection = (groups[branch_id].nil? ? [] : groups[branch_id]).map do |group| child_groups = groups[group.id] || [] page_hash = { title: group.label, key: group.id, folder: true, href: method("edit_admin_cms_site_group_path".sub('site_site','site')).call({site_id: @site.id, id: group.id, format: :js}) } if lazy && !top_node if !(child_groups.empty? && (items[group.id] || []).empty?) # add lazy flag page_hash.merge!({lazy: true}) end else # add child groups/folders child_contents = [] unless child_groups.empty? child_contents = (fancytree_grouped_hash(groups, items, group.id, false, false, lazy, &labelling)) end child_items = items[group.id] || [] unless child_items.empty? child_items.each do |item| child_contents << { title: labelling.call(item), key: item.id, href: method("edit_admin_cms_site_#{item_model}_path".sub('site_site','site')).call({site_id: @site.id, id: item.id, format: :js})} end end page_hash.merge!({folder: true, children: child_contents}) end if top_node # just return the children, skip the root node child_contents else # page and collection as children page_hash end end if top_node if new_link # add a link to add an item collection = collection.first # remove array nesting grouped_type = groups[branch_id].first.grouped_type.underscore.split('/').last html = link_to content_tag(:i, '', :class => 'icon-plus').concat(t(:new_link, :scope => 'admin.cms.groups')), eval("admin_cms_new_#{grouped_type}_group_path(site_id: #{@site.id})") collection << { title: html } end elsif !defined?(page_hash) && collection.empty? # this is a leaf node, we just return the child_items child_items = items[branch_id] || [] unless child_items.empty? child_items.each do |item| collection << { title: labelling.call(item), key: item.id, href: method("edit_admin_cms_site_#{item_model}_path".sub('site_site','site')).call({site_id: @site.id, id: item.id, format: :js})} end end end collection end # simplify standard calls for grouped items def fancytree_group_select_hash(groups, items, labelling) fancytree_grouped_hash(groups, items, nil, true, true, &labelling) end def fancytree_label_for(item) case item when Cms::File # need not be an image! item.is_image? ? image_tag(item.file.url(:mini), class: :fullsize, alt: nil) + ' ' + item.label : item.label else item.label end end # any collection is transformed into a hash ordered by parent_id, for building fancytrees def collection_to_parent_id_ordered_hash(collection) hash = {} collection.inject(hash) do |hash, item| hash[item.parent_id] ||= [] hash[item.parent_id] << item hash end end def options_for_page_select(site, from_page = nil, current_page = nil, depth = 0, exclude_self = true, spacer = ' -') current_page ||= site.pages.root return [] if (current_page == from_page && exclude_self) || !current_page out = [] out << [ "#{spacer*depth}#{current_page.label}", current_page.id ] unless current_page == from_page child_pages = Cms::Page.all.where(parent_id: current_page.id, site_id: site.id) child_pages.each do |child| opt = options_for_page_select(site, from_page, child, depth + 1, exclude_self, spacer) out += opt end if child_pages.size.nonzero? return out.compact end def options_for_group_select(site, from=nil, type=nil, current=nil, depth=0, exclude_self=true, spacer=' -') type ||= from.grouped_type unless from.nil? return [] if type.nil? current ||= site.groups.root.where(grouped_type: type).first return [] if (current == from && exclude_self) || !current out = [] label = current.parent_id.nil? ? t(:none, :scope => 'admin.cms.groups') : current.label out << [ "#{spacer*depth}#{label}", current.id ] unless current == from child_pages = Cms::Group.all.where(parent_id: current.id, site_id: site.id, grouped_type: type) child_pages.each do |child| opt = options_for_group_select(site, from, type, child, depth + 1, exclude_self, spacer) out += opt end if child_pages.size.nonzero? return out.compact end # much simpler call with defaults to options_for_group_select def simple_options_group_select_for(obj) options_for_group_select(obj.site || @site, nil, obj.class.name, nil, 0, false) end # hierarchical hash with group image contents across all levels def image_content_for_group(group, group_name=nil) images = [] unless group.nil? images = group.files.images.map{|i| {src: i.file.url(:original), normal: i.file.url(:resized), thumb: i.file.url(:cms_thumb), title: i.description, group: group_name || '' }} group.children.each do |subgroup| images << image_content_for_group(subgroup, subgroup.label) end end images end def content_for_ajax(name, content = nil, options = {}, &block) if block_given? options = content if content content = capture(&block) end if request.xhr? && (content || block_given?) # Render a javascript_tag for jquery update of target or name javascript_tag "$('##{options[:target] || name}').html('#{escape_javascript(content)}')" else content_for(name, content, options) nil end end # Override active_link_to here to also compare local href hashes # in order to get the nav tabs to work. def is_active_link?(url, condition = nil) # check hashes against controller name active_hash = (url[/^#[_a-z]*/i] || '').sub('#','') unless active_hash.blank? if %(sites pages layouts snippets files).include?(controller_name) if action_name == 'edit' return active_hash == 'meta_pane' else return active_hash == controller_name end else # pages is the default active tab return active_hash == 'pages' end else url = url_for(url).sub(/\?.*/, '') # ignore GET params case condition when :inclusive, nil !request.fullpath.match(/^#{Regexp.escape(url).chomp('/')}(\/.*|\?.*)?$/).blank? when :exclusive !request.fullpath.match(/^#{Regexp.escape(url)}\/?(\?.*)?$/).blank? when Regexp !request.fullpath.match(condition).blank? when Array controllers = [*condition[0]] actions = [*condition[1]] (controllers.blank? || controllers.member?(params[:controller])) && (actions.blank? || actions.member?(params[:action])) when TrueClass true when FalseClass false end end end # Generates a visible title for the current context def current_context_title(tag=:span, separator = ' | ') if %(sites pages layouts snippets files).include?(controller_name) instance = eval("@#{controller_name.singularize}") text = [t("cms/#{controller_name.singularize}", :scope => 'activerecord.models'), (instance.nil? ? nil : instance.label)].compact.join(separator) tag.nil? ? text : content_tag(tag, text) else '' end end # This is a helper for passing the current subpage's slug to the Comfy Layout def subpage_slug if defined?(@cms_subpage) @cms_subpage.slug else 'content_' + (@cms_subcontent_index = (defined?(@cms_subcontent_index) ? (@cms_subcontent_index += 1) : 1)).to_s.strip end end # Helper for generating a gallery image tag def image(path, caption=true, klass='fancybox') path_tokens = path.split('/') image_name = path_tokens.pop groups = path_tokens.empty? ? @cms_site.mirrors.map{|s| s.groups.files.root } : @cms_site.mirrors.map{|s| s.groups.files.where(['hierarchy_path LIKE ?', path_tokens.join('/')]).first }.compact return '' if groups.nil? || groups.empty? image = @cms_site.mirrors.map{|s| s.files.images.where(['label LIKE ? AND group_id IN (?)', image_name, groups.map(&:id)]).first }.compact.first return '' if image.nil? || image.file.nil? html = link_to image_tag(image.file.url(:resized)), image.file.url, class: klass, title: image.description html << content_tag(:span, image.description, class: 'caption') content_tag(:div, html, class: klass + '-wrapper') end # Helper for generating a gallery image tag displaying an image's original size def original_size_image(path, caption=true, klass='fancybox') path_tokens = path.split('/') image_name = path_tokens.pop groups = path_tokens.empty? ? @cms_site.mirrors.map{|s| s.groups.files.root } : @cms_site.mirrors.map{|s| s.groups.files.where(['hierarchy_path LIKE ?', path_tokens.join('/')]).first }.compact return '' if groups.nil? || groups.empty? image = @cms_site.mirrors.map{|s| s.files.images.where(['label LIKE ? AND group_id IN (?)', image_name, groups.map(&:id)]).first }.compact.first return '' if image.nil? || image.file.nil? html = link_to image_tag(image.file.url), image.file.url, class: klass, title: image.description html << content_tag(:span, image.description, class: 'caption') content_tag(:div, html, class: klass + '-wrapper') end # Override the def comfy_form_for(record, options = {}, &proc) options[:builder] = ComfortableMexicanSofa::FormBuilder options[:type] ||= :horizontal formatted_form_for(record, options, &proc) end def click_action_for(dom_id, model, action) if %w(site layout page snippet file).include?(model.to_s) && %w(new update destroy).include?(action.to_s) action_url_method = [action.to_s, 'admin_cms_site', (model.to_s == 'site' ? nil : model.to_s), 'path'].compact.join('_') unless @site.nil? || @site.new_record? action_url = action_url_method.concat "(:site_id => #{@site.id})" end end "$('##{dom_id}').attr('href','#{eval(action_url || action_url_method)}'); initializeTreeTab('#{model}s-tree');" end # renders hidden fields with behavior to copy from the data-attribute=true field on submit def data_copy_field_for(model, attribute, data_tag=nil) data_tag ||= attribute hidden_field_tag "#{model}[#{attribute}]", eval("@#{model}.#{attribute}"), id: "copy_#{data_tag}", data: {copy: data_tag} end # Creates formatted form fields according to contact_form_definitions def contact_form_field(form_builder, contact_form, field, value=nil) value ||= @contact.getFieldValue(field) contact_field_definition = contact_form.contact_field_options_for(field).symbolize_keys wrap_tag = contact_form.site.contact_form_wrap_tag translations = contact_form.contact_field_translations options_for_html = {} %w(width height prepend append in label values mandatory).each do |dim| options = contact_field_definition[dim.to_sym] next if options.blank? || (options.is_a?(Enumerable) && options.empty?) options_for_html[dim] = contact_field_definition[dim.to_sym] end unless contact_field_definition[:options].blank? options_for_html['options'] ||= {} contact_field_definition[:options].keys.each do |k| options_for_html['options'][t(k, :scope => "cms.contact_form.#{field}")] = contact_field_definition[:options][k] end end label = t((options_for_html[:label].blank? ? (translations[field] || field) : options_for_html[:label]), :scope => 'cms.contact_form.fields') options_for_html[:label] = h(label) case @cms_site.css_framework.underscore.to_sym when :gumby gumby_field_tag(form_builder, contact_field_definition[:type], field, options_for_html, value, wrap_tag) else bootstrap_field_tag(form_builder, contact_field_definition[:type], field, options_for_html, value, wrap_tag) end end end def gumby_field_tag(form_builder, type, field, options_for_html, value, wrap_tag=nil) prepend = options_for_html.delete('prepend') append = options_for_html.delete('append') mandatory = options_for_html.delete('mandatory') label = options_for_html.delete(:label) + (mandatory ? ' *' : '') options_for_html.merge!({:placeholder => (value.blank? ? label : value)}) if mandatory options_for_html.merge!({:required => true}) end klasses = %w(field) klasses << 'completed' unless value.blank? label_tag = content_tag(:label, label, { class: 'inline', for: "contact[#{field}]" }) html = case type.underscore.to_sym when :string, :datetimer text_field_tag "contact[#{field}]", value, options_for_html.merge!({class: 'input'}) when :password password_field_tag "contact[#{field}]", value, options_for_html.merge!({class: 'input'}) when :number number_field_tag "contact[#{field}]", value, options_for_html.merge!({class: 'input'}) when :email email_field_tag "contact[#{field}]", value, options_for_html.merge!({class: 'input'}) when :phone phone_field_tag "contact[#{field}]", value, options_for_html.merge!({class: 'input'}) when :country options = localized_country_options_for_select(value, [:DE, :AT, :CH, :GB, :US]) label_tag + content_tag(:div, select_tag("contact[#{field}]", options, options_for_html), class: 'picker') when :select options = options_for_select((options_for_html.delete('options') || {}), value) label_tag + content_tag(:div, select_tag("contact[#{field}]", options, options_for_html), class: 'picker') when :checkbox content_tag(:label, label + check_box_tag("contact[#{field}]", 1, !value.false?, options_for_html.merge!({class: 'input'})), { for: "contact[#{field}]"}) when :textarea, :text label_tag + text_area_tag("contact[#{field}]", value, options_for_html.merge!({class: 'input'})) else # Text field text_field_tag "contact[#{field}]", value, options_for_html.merge!({class: 'input'}) end unless prepend.blank? html = content_tag(:span, content_tag(:i, '', class: prepend), class: 'adjoined') + html klasses << 'prepend' end unless append.blank? html = html + content_tag(:span, content_tag(:i, '', class: append), class: 'adjoined') klasses << 'append' end html = content_tag(wrap_tag || :li, html, class: klasses.join(' ')) html end def bootstrap_field_tag(form_builder, type, field, options_for_html, value, wrap_tag=nil) html = case type.underscore.to_sym when :text form_builder.textarea field, options_for_html when :password form_builder.password_field field, options_for_html when :number form_builder.number_field field, options_for_html when :email form_builder.email_field field, options_for_html when :phone form_builder.phone_field field, options_for_html when :select form_builder.select field, options_for_html.delete(:options), options_for_html when :checkbox options_for_html[:values].nil? ? / form_builder.check_box(options_for_html.delete(:values), options_for_html) / : form_builder.check_box(field, options_for_html) when :datetime form_builder.text_field field, options_for_html.merge!({class: 'datetime'}) else # Text field form_builder.text_field field, options_for_html end html = content_tag(wrap_tag, html, class: :field) unless wrap_tag.blank? html end
class Category < ActiveRecord::Base has_many :articles scope :top, -> { select("categories.id, categories.name, COUNT(articles.id) AS articles_count"). joins(:articles). group("categories.id"). order("articles_count DESC") } end
require_relative 'pitch' require 'set' module Dodecaphony class Row include Enumerable attr_reader :original_row, :intervals alias_method :pitches, :original_row def initialize tone_row self.original_row = create_row_with_pitches(tone_row) validate_size_of original_row self.intervals = create_list_with_intervals(original_row, starting_pitch) end def to_s to_a.join(" ") end def to_a pitches.each_with_object([]) do |pitch, row| row << pitch.name end end def spell_with_sharps normalize_row(:spell_as_sharp) end def spell_with_flats normalize_row(:spell_as_flat) end def == other (other.pitches).zip(pitches).all? do |pitches| pitches[0] == pitches[1] end end def each &block pitches.each &block end private attr_writer :intervals, :original_row def create_list_with_intervals(row, first_pitch) row_list = row.each_with_object({}) do |pitch, hash| distance = first_pitch.distance_from pitch validate_uniqueness_of distance, hash hash[distance] = pitch end finalize_pitches(row_list) end def finalize_pitches(row_list) row_list[12] = starting_pitch row_list end def starting_pitch original_row[0] end def create_row_with_pitches tone_row tone_row.each_with_object([]) do |pitch, row| row << Pitch.new(pitch) end end def validate_size_of row row_size = row.to_set.length unless row_size == 12 raise ArgumentError, "incorrect number of pitches (#{row_size}) in row" end end def validate_uniqueness_of distance, hash if hash.has_key? distance raise ArgumentError, "duplicate pitch (#{hash[distance].name})" end end def normalize_row message original_row.each_with_object([]) do |pitch, row| row << pitch.send(message) end end end end
require 'minitest/autorun' require 'minitest/reporters' Minitest::Reporters.use! class DowncaseTest < MiniTest::Test def setup @other_str = 'abc' @expected = 'xyz' end def test_downcase assert_equal(@expected, 'XYZ'.downcase) end def test_different_other_downcase_string refute_equal(@other_str, 'XYZ'.downcase) end end
#!/usr/bin/env ruby require 'yaml' require 'ostruct' module Visage class CollectdProfile def initialize(opts={}) @profile = opts[:profile] end class << self attr_accessor :profiles def get(id) id.gsub!(/\s+/, '+') if found = @profiles.find {|p| p[1]["splat"] == id } OpenStruct.new(found[1]) else nil end end def all # here be ugliness profiles = @profiles.to_a.sort_by { |profile| profile[1]["order"] }.map { |profile| OpenStruct.new(profile[1].merge({'name' => profile[0]})) } end end end end
class LaserGemsController < ApplicationController include ApplicationHelper before_action :authenticate_user!, only: [:add_comment , :add_tag] before_action :load_gem , only: [:show , :add_tag , :add_comment] impressionist actions: [ :index , :add_tag , :add_comment ] # GET /laser_gems def index @q = LaserGem.includes(:gem_spec, :gem_git, :taggings => :tag). joins( :gem_spec ). ransack(params[:q]) @laser_count = @q.result(distinct: true) page = params[:page].to_i page = 1 if page < 1 or page > 20 @laser_gems = @laser_count.paginate(page: page, per_page: 20) respond_to do |format| format.html format.js end end # GET /laser_gems/gem_name def show redirect_to(root_path) unless (@laser_gem and @laser_gem.gem_spec) impressionist(@laser_gem) if @laser_gem end def add_tag if msg = tag_validation( params[:tag] ) flash[:notice] = "Please insert a valid tag. " + msg render :show else @laser_gem.tag_list.add(params[:tag]) @laser_gem.save redirect_to laser_gem_path(@laser_gem.name) end end def add_comment @comment = Comment.new(body: params[:comment_body], user: current_user, laser_gem: @laser_gem) if @comment.save redirect_to laser_gem_path(@laser_gem.name) else flash[:notice] = "Please insert a valid comment." render :show end end def has_owner_rights? return false unless current_user @laser_gem.is_gem_owner?(current_user) end helper_method :has_owner_rights? private def load_gem @laser_gem = LaserGem.find_by_name(params[:name]) end end
require 'test_helper' class ItinerariesControllerTest < ActionDispatch::IntegrationTest setup do @itinerary = itineraries(:one) end test "should get index" do get itineraries_url, as: :json assert_response :success end test "should create itinerary" do assert_difference('Itinerary.count') do post itineraries_url, params: { itinerary: { trip_id: @itinerary.trip_id } }, as: :json end assert_response 201 end test "should show itinerary" do get itinerary_url(@itinerary), as: :json assert_response :success end test "should update itinerary" do patch itinerary_url(@itinerary), params: { itinerary: { trip_id: @itinerary.trip_id } }, as: :json assert_response 200 end test "should destroy itinerary" do assert_difference('Itinerary.count', -1) do delete itinerary_url(@itinerary), as: :json end assert_response 204 end end
class Scene < ActiveRecord::Base has_many :responses, :dependent => :destroy belongs_to :user validates :title, :description, presence: true delegate :name, :to => :user, :allow_nil => true, :prefix => true scope :ordered, order("created_at DESC") scope :visible, where(:hidden => false) def best_scenario best_first_response = responses.best_child_by_parent_id(self.id, 0) if best_first_response then best_first_response.best_scenario else [] end end def scenarios_response_ids best_first_responses = responses.best_children_by_parent_id(self.id, 0) best_first_responses.map(&:scenarios_response_ids).flatten end def self.find_visible_scenes visible.ordered end end
class TimelinesController < ApplicationController def show users = current_user.followings @articles = users.joins(:articles).select("articles.*").order("likes_count DESC").limit(10) end end
class AddCaseSizeToBookedItem < ActiveRecord::Migration def change add_column :booked_items, :case_size, :string end end
# -*- mode: ruby -*- # vi: set ft=ruby : $initial_script = <<-'SCRIPT' echo "" echo "apt update" sudo apt-get update # echo "" echo "apt upgrade" sudo apt -y upgrade # echo "" echo "install python and ansible" sudo apt install -y python3-pip sudo apt install -y build-essential libssl-dev libffi-dev python3-dev sudo apt install -y ansible # echo "" echo "ansible galaxy" sudo ansible-galaxy collection install community.general # echo "" echo "copy ansible config files" sudo cp /home/vagrant/ansible/hosts /root/ sudo cp /home/vagrant/ansible/ansible.cfg /etc/ansible/ # echo "" echo "run ansible playbook" cd /home/vagrant/ansible sudo ansible-playbook dev-playbook.yaml SCRIPT Vagrant.configure("2") do |config| # # ubuntu 20 LTS config.vm.box = "ubuntu/focal64" # # vm is just another host on home network (bridged) # vm can access the outside world. config.vm.network "public_network", ip: "192.168.1.127" config.vm.synced_folder "share", "/vagrant" config.vm.provider "virtualbox" do |vb| # Display the VirtualBox GUI when booting the machine vb.gui = false # Customize the amount of memory on the VM: vb.memory = 4096 vb.cpus = 2 end # # copy ansible files to vm config.vm.provision "file", source: "../ansible", destination: "$HOME/ansible" config.vm.provision "initial", type: "shell", inline: $initial_script end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'katar/version' Gem::Specification.new do |spec| spec.name = "katar" spec.version = Katar::VERSION spec.authors = ["AcMitch"] spec.email = ["adam.cameron.mitchell@gmail.com"] spec.summary = "Katar provides a simple, elegant way to manage and provision a Vagrant box on your local machine." spec.description = "Katar provides a simple, elegant way to manage and provision a Vagrant box on your local machine." spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = ["katar"] spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency 'rspec', '~> 3.3', '>= 3.3.0' spec.add_runtime_dependency 'rubyzip', '~> 1.1', '>= 1.1.7' spec.add_development_dependency "bundler", "~> 1.7" spec.add_development_dependency "rake", "~> 10.0" spec.add_dependency "thor", "~> 0.19.1" end
class Language < ActiveRecord::Base belongs_to :address has_many :snippets, dependent: :destroy validates :title, presence: true end
require 'bundler/gem_tasks' require 'rspec/core/rake_task' task :default => [:test] task :spec => :test desc "run all functional specs in this ruby environment" RSpec::Core::RakeTask.new(:test) do |t| t.pattern = 'spec/*_spec.rb' t.rspec_opts = [ '--format', 'documentation', # This is only really needed once - we can remove it from all the specs #'--require ./spec/spec_helper.rb', '--color', ] end desc "run the specs through all the supported rubies" task :rubies do system("rvm 1.8.7-p370,1.9.3-p194 do rake test") end desc "set up all ruby environments" namespace :bootstrap do task :all_rubies do system("rvm use 1.8.7-p370; bundle install") system("rvm use 1.9.3-p194; bundle install") end end
module A2z module Responses class Image attr_accessor :url, :width, :height def initialize @width = 0 @height = 0 end def width=(value) @width = value.to_i end def height=(value) @height = value.to_i end def self.from_response(data) new.tap do |image| image.url = data['URL'] image.width = data['Width'] image.height = data['Height'] image.freeze end end end end end
class AddDateToEvents < ActiveRecord::Migration def up add_column :events, :date, :date Event.all.each do |event| event.update_column(:date, event.created_at.to_date) end end def down remove_column :events, :date end end