text
stringlengths
10
2.61M
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root to: "hotels#search" resources :fees resources :hotels do collection do get 'search' end end resources :hotsprings resources :restaurants resources :transportaions resources :choice end
class Employer < ActiveRecord::Base belongs_to :user belongs_to :company_type validates :first_name, :presence => true validates :last_name, :presence => true validates :company_name, :presence => true end
require 'set' module MathOpt class SetExpression def initialize(int_start, int_end) @int_start = int_start @int_end = int_end end def to_s "[#{@int_start}, #{@int_end}]" end end class MulExpression attr_reader :variable def initialize number, variable @number = number @variable = variable end def number? @variable.nil? end def var? !@variable.nil? end def to_s return "#{@number}" if number? return "#{@variable}" if @number == "" or @number == 1 or @number.nil? "#{@number} * #{@variable.to_s}" end end class SumExpression def initialize summands @summands = summands end end class Expression < SumExpression def to_s @summands.map { |s| "<#{s}>" }.join " _+_ " end def vars st = [] @summands.each do |s| st.push s.variable end st.to_set end end end
class TempBudgetPlan < ActiveRecord::Base belongs_to :user has_many :recur_budgets, dependent: :destroy # validates :recur_period, :food_budget_v, :finance_budget_v, :shopping_budget_v, :auto_budget_v, :entertainment_budget_v, :other_budget_v, presence: true # validates :food_budget_v, :finance_budget_v, :shopping_budget_v, :auto_budget_v, :entertainment_budget_v, :other_budget_v, allow_blank: true, numericality: {greater_than_or_equal_to: 0.01} # validates :food_budget_v, :finance_budget_v, :shopping_budget_v, :auto_budget_v, :entertainment_budget_v, :other_budget_v, allow_blank: true, numericality: {less_than: 1000000} validates :recur_period, allow_blank: true, numericality: {only_integer: true} validates_uniqueness_of :user_id #getter def food_budget_v denormalize(recur_period,food_budget) unless food_budget.blank? end #setter def food_budget_v=(budget) self.food_budget=normalize(recur_period,budget.to_f.round(2)) end def finance_budget_v denormalize(recur_period,finance_budget) unless finance_budget.blank? end def finance_budget_v=(budget) self.finance_budget=normalize(recur_period,budget.to_f.round(2)) end def shopping_budget_v denormalize(recur_period,shopping_budget) unless shopping_budget.blank? end def shopping_budget_v=(budget) self.shopping_budget=normalize(recur_period,budget.to_f.round(2)) end def auto_budget_v denormalize(recur_period,auto_budget) unless auto_budget.blank? end def auto_budget_v=(budget) self.auto_budget=normalize(recur_period,budget.to_f.round(2)) end def entertainment_budget_v denormalize(recur_period,entertainment_budget) unless entertainment_budget.blank? end def entertainment_budget_v=(budget) self.entertainment_budget=normalize(recur_period,budget.to_f.round(2)) end def other_budget_v denormalize(recur_period,other_budget) unless other_budget.blank? end def other_budget_v=(budget) self.other_budget=normalize(recur_period,budget.to_f.round(2)) end private # this will normalize the budget based on the period entered into monthly rate before saving into database # the database will contain the :recur_period column in case there may be a use of it in the future. def denormalize(period,budget) if period==1 factor=1 elsif period ==2 factor=12 elsif period==3 factor=26 elsif period==4 factor=52 elsif period==5 factor=365 end (budget*12/factor).round(0) end def normalize(period,budget) if period==1 factor=1 elsif period ==2 factor=12 elsif period==3 factor=26 elsif period==4 factor=52 elsif period==5 factor=365 end (budget/12*factor).round(2) end end
Dado('que acesso a pagina de cadastro') do @signup_page.open end Quando('submeto o seguinte formulario de cadastro:') do |table| user = table.hashes.first MongoDB.new.remove_user(user[:email]) @signup_page.create(user) end # Quando('efetuo o meu cadastro completo') do # MongoDB.new.remove_user("gabriel_teste@gmail.com") # find("#fullName").set "Gabriel" # find("#email").set "gabriel_teste@gmail.com" # find("#password").set "pwd123" # click_button "Cadastrar" # end # Quando('efetuo o meu cadastro sem o nome') do # MongoDB.new.remove_user("gabriel.@gmail.com") # find("#email").set "gabriel.@gmail.com" # find("#password").set "teste123" # click_button "Cadastrar" # end # Entao('vejo a mensagem de alerta: Oops. Informe seu nome completo!') do # alert = find(".alert-dark") # expect(alert.text).to eql "Oops. Informe seu nome completo!" # end # Quando('efetuo o meu cadastro sem o email') do # find("#fullName").set "Gabriel" # find("#password").set "teste123" # click_button "Cadastrar" # end # Entao('vejo a mensagem de alerta: Oops. Informe um email valido!') do # alert = find(".alert-dark") # expect(alert.text).to eql "Oops. Informe um email vรกlido!" # end # Quando('efetuo o meu cadastro com email incorreto') do # find("#fullName").set "Gabriel" # find("#email").set "teste_gmail.com" # find("#password").set "teste123" # click_button "Cadastrar" # end # Quando('efetuo o meu cadastro sem a senha') do # find("#fullName").set "Gabriel" # find("#email").set Faker::Internet.free_email # click_button "Cadastrar" # end # Entao('vejo a mensagem de alerta: Oops. Informe sua senha secreta!') do # alert = find(".alert-dark") # expect(alert.text).to eql "Oops. Informe sua senha secreta!" # end
class Group < ApplicationRecord has_many :questions belongs_to :user has_many :responses has_many :posts end
# frozen_string_literal: true class AllowedAction < ::ApplicationRecord def table_id = 'ald' belongs_to :role validates :name, :role, presence: true validates :name, inclusion: { in: ->(_) { ::AllowedAction.all_actions }, message: 'ๆŒ‡ๅฎšใงใใชใ„ใ‚ขใ‚ฏใ‚ทใƒงใƒณ(%<value>)' } class << self def default_actions = ::Query.fields.keys + %w[login signup] def console_actions = %w[graphiql console].freeze def all_actions = (::Mutation.fields.keys + default_actions + console_actions).uniq end end module Types module Enums class ActionEnum < ::Types::Enums::BaseEnum ::AllowedAction.all_actions.each do |action| value action, value: action end end end end
class AddStandardToProducts < ActiveRecord::Migration[5.1] def change add_column :products, :standard, :string, limit: 1, default: 'N' end end
class WaybillReportNew < Report @@wb_top_height = 60 @@wb_part2_width = 350 @@p1_height = 300 @@other_pages_height = 420 attr_accessor :curr_y def initialize super :page_size => 'A4', :margin => [15, 15] end def to_pdf(waybill) font "#{Rails.root}/lib/Arial Unicode.ttf", :size => 6 print_exemplar(waybill, '1') start_new_page print_exemplar(waybill, '2') start_new_page print_exemplar(waybill, '3') render end protected def print_exemplar(waybill, ex) start_page = page_count print_header(waybill, ex) move_down 2 print_items(waybill, ex) end_page = page_count # numbering pages pages = end_page - start_page + 1 (1..pages).each do |i| go_to_page start_page + i - 1 txt = "แƒ’แƒ•แƒ”แƒ แƒ“แƒ˜ #{i} / #{pages}-แƒ“แƒแƒœ" txt_w = width_of txt draw_text 'แƒ“แƒแƒ›แƒ–แƒแƒ“แƒ”แƒ‘แƒฃแƒšแƒ˜แƒ http://sagadasaxado.com -แƒ–แƒ”', :at => [0, 0] draw_text txt, :at => [bounds.right - bounds.left - txt_w, 0] end end def print_header(waybill, ex) text "แƒกแƒแƒกแƒแƒฅแƒแƒœแƒšแƒ แƒ–แƒ”แƒ“แƒœแƒแƒ“แƒ”แƒ‘แƒ˜ โ„–#{waybill.wb_invoice.number}", :size => 12, :align => :center text "I แƒœแƒแƒฌแƒ˜แƒšแƒ˜", :size => 8, :align => :center print_danarti1 print_cell1(ex) print_cell2(waybill) print_top_left(waybill) print_top_right(waybill) print_addresses(waybill) print_transport(waybill) end def print_items(waybill, ex) items = waybill.wb_invoice.items print_remaining(waybill, ex, items, 0) end def print_remaining(waybill, ex, items, index) return if (index > items.size - 1) first_page = index == 0 if first_page print_items_header else start_new_page table([['แƒกแƒแƒกแƒแƒฅแƒแƒœแƒšแƒ แƒ–แƒ”แƒ“แƒœแƒแƒ“แƒ”แƒ‘แƒ˜แƒก แƒ“แƒแƒœแƒแƒ แƒ—แƒ˜', waybill.wb_invoice.number]], :column_widths => [300, 100], :cell_style => {:size => 12}) do column(0).style(:borders => []) end print_danarti1 print_cell1(ex) print_items_header end max_height = first_page ? @@p1_height : @@other_pages_height height = 0 page_summary = 0 page_count = 0 order = 1 empty_y1 = nil empty_y2 = nil while(height < max_height) item = items.size > index ? items[index] : nil item_table = make_item_table(item, order) item_table.draw index += 1 order += 1 height += item_table.height page_summary += item.line_total if item page_count += item.count if item unless item empty_y1 = y unless empty_y1 empty_y2 = y end end print_empty_cells(empty_y1, empty_y2) if empty_y1 print_page_summary_row(page_summary, page_count) print_footer(waybill, !first_page) print_remaining(waybill, ex, items, index) end private def print_empty_cells(empty_y1, empty_y2) return if empty_y1 == empty_y2 stroke_color('ff0000') [[20, empty_y1 - 10, @@wb_part2_width - 20, empty_y1 - 10], [20, empty_y1 - 10, @@wb_part2_width - 20, empty_y2 - 10], [20, empty_y2 - 10, @@wb_part2_width - 20, empty_y2 - 10], [20, empty_y2 - 10, @@wb_part2_width - 20, empty_y1 - 10],].each { |p| stroke_line(*p) } stroke_color('000000') end def print_items_header p2 = @@wb_part2_width p3 = p3_width # general part table([['II แƒœแƒแƒฌแƒ˜แƒšแƒ˜', ' ', 'III แƒœแƒแƒฌแƒ˜แƒšแƒ˜'], ['', '', 'แƒ’แƒแƒ›แƒแƒ˜แƒงแƒ”แƒœแƒ”แƒ‘แƒ แƒ›แƒฎแƒแƒšแƒแƒ“ แƒ“แƒ˜แƒกแƒขแƒ แƒ˜แƒ‘แƒฃแƒชแƒ˜แƒ˜แƒก แƒฌแƒ”แƒกแƒ˜แƒ— แƒ›แƒ˜แƒฌแƒแƒ“แƒ”แƒ‘แƒ˜แƒกแƒแƒก']], :column_widths => [p2, 5, p3], :cell_style => {:padding => 2, :align => :center}) do row(0).style(:borders => [], :size => 8) row(1).column(0).style(:borders => []) row(1).column(1).style(:borders => []) row(1).column(2).style(:background_color => 'ffff00') end # column headings table ([['', 'แƒกแƒแƒฅแƒแƒœแƒšแƒ˜แƒก แƒ“แƒแƒกแƒแƒฎแƒ”แƒšแƒ”แƒ‘แƒ', 'แƒ–แƒแƒ›แƒ˜แƒก แƒ”แƒ แƒ—แƒ”แƒฃแƒšแƒ˜', 'แƒ แƒแƒแƒ“แƒ”แƒœแƒแƒ‘แƒ', 'แƒ”แƒ แƒ—แƒ”แƒฃแƒšแƒ˜แƒก แƒคแƒแƒกแƒ˜*', 'แƒ—แƒแƒœแƒฎแƒ*', ' ', 'แƒ›แƒ˜แƒฌแƒแƒ“แƒ”แƒ‘แƒ˜แƒก แƒ—แƒแƒ แƒ˜แƒฆแƒ˜, แƒกแƒแƒแƒ—แƒ˜, แƒฌแƒฃแƒ—แƒ˜', 'แƒ›แƒ˜แƒ˜แƒฆแƒ (แƒกแƒแƒฎแƒ”แƒšแƒ˜, แƒ’แƒ•แƒแƒ แƒ˜, แƒžแƒ˜แƒ แƒแƒ“แƒ˜ แƒœแƒแƒ›แƒ”แƒ แƒ˜, แƒฎแƒ”แƒšแƒ›แƒแƒฌแƒ”แƒ แƒ)', 'แƒฉแƒแƒแƒ‘แƒแƒ แƒ (แƒกแƒแƒฎแƒ”แƒšแƒ˜, แƒ’แƒ•แƒแƒ แƒ˜, แƒžแƒ˜แƒ แƒแƒ“แƒ˜ แƒœแƒแƒ›แƒ”แƒ แƒ˜, แƒฎแƒ”แƒšแƒ›แƒแƒฌแƒ”แƒ แƒ)', 'แƒกแƒแƒฅแƒแƒœแƒšแƒ˜แƒก แƒ’แƒแƒ“แƒแƒชแƒ”แƒ›แƒ˜แƒก แƒกแƒแƒคแƒฃแƒซแƒ•แƒ”แƒšแƒ˜ (แƒ–แƒ”แƒ“แƒœแƒแƒ“แƒ”แƒ‘แƒ˜, แƒฃแƒ™แƒแƒœ แƒ“แƒแƒ‘แƒ แƒฃแƒœแƒ”แƒ‘แƒ)'], ['','I','II','III','IV','V','','VI','VII','VIII','IX']], :column_widths => p2_column_widths + [5] + p3_column_widths) do column(6).style(:borders => []) row(0..1).style(:valign => :center, :align => :center) row(0).column(0..5).style(:size => 8) row(1).style(:padding => 1) row(1).column(0..5).style(:background_color => 'eeeeee') row(1).column(7..10).style(:background_color => 'eeeeee') end end def make_item_table(item, order) ord = item ? order.to_s : '' name = item ? item.production.name : '' measure = item ? (item.measure ? item.measure : item.production.measure) : ' ' count = item ? format_amount(item.count) : ' ' price = item ? format_amount(item.price) : ' ' line_total = item ? format_amount(item.line_total) : ' ' widths = p2_column_widths + [5] + p3_column_widths make_table([[ord,name,measure,count,price,line_total, '','','','','']], :column_widths => widths) do column(0).style(:padding => 0, :align => :center) column(2).style(:align => :center) column(3..5).style(:align => :right) column(6).style(:borders => []) row(0).style(:valign => :center) end end def print_page_summary_row(page_summary, page_count) w2 = p2_column_widths w3 = p3_column_widths widths = [w2[0] + w2[1] + w2[2], w2[3], w2[4] - 20, 20, w2[4], 5, w3[0] + w3[1] + w3[2] + w3[3]] table([['', format_amount(page_count),'','10', format_amount(page_summary), '', amount_spelled(page_summary)],['','','','','','','แƒ—แƒแƒœแƒฎแƒ แƒกแƒฃแƒš (แƒกแƒ˜แƒขแƒงแƒ•แƒ˜แƒ”แƒ แƒแƒ“)']], :column_widths => widths) do columns(0).style(:borders => []) column(1).style(:align => :right) column(2).style(:borders => []) column(3).row(0).style(:align => :center, :background_color => 'eeeeee') column(4).style(:align => :right) column(5).style(:borders => []) column(6).row(0).style(:borders => [:bottom], :align => :center) row(1).style(:borders => [], :align => :center, :padding => 1, :size => 5) end end def print_footer(waybill, not_first = false) text '* แƒ“แƒฆแƒ’-แƒก แƒ’แƒแƒ“แƒแƒ›แƒฎแƒ“แƒ”แƒšแƒ˜แƒกแƒแƒ—แƒ•แƒ˜แƒก แƒ“แƒฆแƒ’-แƒก แƒฉแƒแƒ—แƒ•แƒšแƒ˜แƒ—; แƒแƒฅแƒชแƒ˜แƒ–แƒ˜แƒก แƒ’แƒแƒ“แƒแƒ›แƒฎแƒ“แƒ”แƒšแƒ˜แƒกแƒแƒ—แƒ•แƒ˜แƒก แƒแƒฅแƒชแƒ˜แƒ–แƒฃแƒ  แƒกแƒแƒฅแƒแƒœแƒšแƒ”แƒ–แƒ”, แƒ“แƒฆแƒ’-แƒก แƒ“แƒ แƒแƒฅแƒชแƒ˜แƒ–แƒ˜แƒก แƒฉแƒแƒ—แƒ•แƒšแƒ˜แƒ—', :size => 5 move_down 10 page_width = bounds.right - bounds.left w1 = page_width / 2 - 25 # 11 & 13 unless not_first table([['11',waybill.wb_invoice.sender_details,'','13',waybill.wb_invoice.receiver_details], ['','แƒ’แƒแƒ›แƒงแƒ˜แƒ“แƒ•แƒ”แƒšแƒ˜ (แƒ’แƒแƒ›แƒ’แƒ–แƒแƒ•แƒœแƒ˜) --- แƒ—แƒแƒœแƒแƒ›แƒ“แƒ”แƒ‘แƒแƒ‘แƒ, แƒกแƒแƒฎแƒ”แƒšแƒ˜ แƒ“แƒ แƒ’แƒ•แƒแƒ แƒ˜', '', '', 'แƒ›แƒงแƒ˜แƒ“แƒ•แƒ”แƒšแƒ˜ (แƒ›แƒ˜แƒ›แƒฆแƒ”แƒ‘แƒ˜) --- แƒ—แƒแƒœแƒแƒ›แƒ“แƒ”แƒ‘แƒแƒ‘แƒ, แƒกแƒแƒฎแƒ”แƒšแƒ˜ แƒ“แƒ แƒ’แƒ•แƒแƒ แƒ˜']], :column_widths => [20, w1, 5, 20, w1+5]) do row(0).style(:align => :center) row(0).column(2).style(:borders => []) row(0).column(0).style(:background_color => 'eeeeee') row(0).column(3).style(:background_color => 'eeeeee') row(0).column(1).style(:borders => [:bottom]) row(0).column(4).style(:borders => [:bottom]) row(1).style(:borders => [], :size => 5, :padding => 1, :align => :center) end else table([['','','','13',waybill.wb_invoice.receiver_details], ['','', '', '', 'แƒ›แƒงแƒ˜แƒ“แƒ•แƒ”แƒšแƒ˜ (แƒ›แƒ˜แƒ›แƒฆแƒ”แƒ‘แƒ˜) --- แƒ—แƒแƒœแƒแƒ›แƒ“แƒ”แƒ‘แƒแƒ‘แƒ, แƒกแƒแƒฎแƒ”แƒšแƒ˜ แƒ“แƒ แƒ’แƒ•แƒแƒ แƒ˜']], :column_widths => [20, w1, 5, 20, w1+5]) do row(0).style(:align => :center) row(0).column(2).style(:borders => []) #row(0).column(0).style(:background_color => 'eeeeee') row(0).column(3).style(:background_color => 'eeeeee') row(0).column(0..1).style(:borders => []) row(0).column(4).style(:borders => [:bottom]) row(1).style(:borders => [], :size => 5, :padding => 1, :align => :center) end end # 12 & 14 move_down 30 unless not_first table([['12', '', 'แƒจแƒขแƒแƒ›แƒžแƒ˜ (แƒ‘แƒ”แƒญแƒ”แƒ“แƒ˜)', '', '14', '', 'แƒจแƒขแƒแƒ›แƒžแƒ˜ (แƒ‘แƒ”แƒญแƒ”แƒ“แƒ˜)'],['', 'แƒฎแƒ”แƒ›แƒšแƒ›แƒแƒฌแƒ”แƒ แƒ', '', '', '', 'แƒฎแƒ”แƒšแƒ›แƒแƒฌแƒ”แƒ แƒ', '']], :column_widths => [20, 100, w1-100, 5, 20, 100, w1 - 95]) do row(1).style(:borders => [], :size => 5, :align => :center, :padding => 1) row(0).style(:align => :center) column(2).style(:borders => []) column(3).style(:borders => []) column(6).style(:borders => []) row(0).column(0).style(:background_color => 'eeeeee') row(0).column(4).style(:background_color => 'eeeeee') row(0).column(1).style(:borders => [:bottom]) row(0).column(5).style(:borders => [:bottom]) end else table([['', '', '', '', '14', '', 'แƒจแƒขแƒแƒ›แƒžแƒ˜ (แƒ‘แƒ”แƒญแƒ”แƒ“แƒ˜)'],['', '', '', '', '', 'แƒฎแƒ”แƒšแƒ›แƒแƒฌแƒ”แƒ แƒ', '']], :column_widths => [20, 100, w1-100, 5, 20, 100, w1 - 95]) do row(1).style(:borders => [], :size => 5, :align => :center, :padding => 1) row(0).style(:align => :center) column(0..3).style(:borders => []) column(3).style(:borders => []) column(6).style(:borders => []) #row(0).column(0).style(:background_color => 'eeeeee') row(0).column(4).style(:background_color => 'eeeeee') #row(0).column(1).style(:borders => [:bottom]) row(0).column(5).style(:borders => [:bottom]) end end # 15 move_down 30 table([['', make_date_table(waybill.wb_invoice.delivery_date, '15')],['','แƒ แƒ˜แƒชแƒฎแƒ•แƒ˜, แƒ—แƒ•แƒ”(แƒกแƒ˜แƒขแƒงแƒ•แƒ˜แƒ”แƒ แƒแƒ“), แƒฌแƒ”แƒšแƒ˜']], :cell_style => {:borders => []}, :column_widths => [w1 + 25]) do row(1).style(:align => :center, :size => 5, :padding => 1) end end def print_danarti1 width = width_of 'แƒ“แƒแƒœแƒแƒ แƒ—แƒ˜ โ„–1' draw_text 'แƒ“แƒแƒœแƒแƒ แƒ—แƒ˜ โ„–1', :at => [bounds.right - width, bounds.top - 11] end def print_cell1(ex) items = [['1', '', "แƒ”แƒ’แƒ–แƒ”แƒ›แƒžแƒšแƒแƒ แƒ˜ #{ex}"]] tbl = make_table(items, :cell_style => {:padding => 4, :align => :center}, :column_widths => [15, 5, 60]) do column(0).style({:background_color => 'eeeeee'}) column(1).style({:borders => []}) end width = tbl.width + 1 height = tbl.height + 1 p_x = bounds.right - width self.curr_y = y - bounds.absolute_bottom - 5 bounding_box [p_x, curr_y], :width => width, :height => height do tbl.draw end end def make_date_table(dt, num = '2') day = dt.strftime("%d") if dt month = month_name(dt) if dt year = dt.strftime("%Y") if dt items = [[num, '', day, month, year]] make_table(items, :cell_style => {:padding => 4, :align => :center}, :column_widths => [15, 5, 20, 60, 40]) do column(0).style({:background_color => 'eeeeee'}) column(1).style({:borders => []}) end end def print_cell2(waybill) tbl = make_date_table(waybill.wb_invoice.opdate) width = tbl.width + 1 height = tbl.height + 10 p_x = (bounds.right - bounds.left - width) / 2 p_y = self.curr_y bounding_box [p_x, p_y], :width => width, :height => height do tbl.draw move_down 1 text 'แƒ แƒ˜แƒชแƒฎแƒ•แƒ˜, แƒ—แƒ•แƒ” (แƒกแƒ˜แƒขแƒงแƒ•แƒ˜แƒ”แƒ แƒแƒ“), แƒฌแƒ”แƒšแƒ˜', :align => :center end end def print_top_left(waybill) width = (bounds.right - bounds.left) / 2 - 2 height = @@wb_top_height self.curr_y = y - bounds.absolute_bottom - 5 bounding_box [0, self.curr_y], :width => width, :height => height do move_down 5 tax_code_box('แƒ’แƒแƒ›แƒงแƒ˜แƒ“แƒ•แƒ”แƒšแƒ˜ (แƒ’แƒแƒ›แƒ’แƒ–แƒแƒ•แƒœแƒ˜)', '3', waybill.wb_invoice.sender_tax_id).draw move_down 3 text waybill.wb_invoice.sender_name, :align => :center, :size => 8 make_horiz_stroke text 'แƒ“แƒแƒกแƒแƒฎแƒ”แƒšแƒ”แƒ‘แƒ แƒแƒœ แƒกแƒแƒฎแƒ”แƒšแƒ˜ แƒ“แƒ แƒ’แƒ•แƒแƒ แƒ˜', :align => :center end end def print_top_right(waybill) width = (bounds.right - bounds.left) / 2 - 2 height = @@wb_top_height bounding_box [width + 4, self.curr_y], :width => width, :height => height do move_down 5 tax_code_box('แƒ›แƒงแƒ˜แƒ“แƒ•แƒ”แƒšแƒ˜ (แƒ›แƒ˜แƒ›แƒฆแƒ”แƒ‘แƒ˜)', '4', waybill.wb_invoice.receiver_tax_id).draw move_down 3 text waybill.wb_invoice.receiver_name, :align => :center, :size => 8 make_horiz_stroke text 'แƒ“แƒแƒกแƒแƒฎแƒ”แƒšแƒ”แƒ‘แƒ แƒแƒœ แƒกแƒแƒฎแƒ”แƒšแƒ˜ แƒ“แƒ แƒ’แƒ•แƒแƒ แƒ˜', :align => :center end end def print_addresses(waybill) opertype = operation_type_table(waybill) addresses = waybill_addresses(waybill) table [[opertype, ' ', addresses]], :cell_style => {:borders => []} end def operation_type_table(waybill) def is_internal(acc) acc.nil? or acc.acc_type == 'FL' end internal_operation = is_internal(waybill.wb_invoice.sender) && is_internal(waybill.wb_invoice.receiver) items = [ ['', '', '', 'แƒ›แƒ˜แƒฌแƒแƒ“แƒ”แƒ‘แƒ', internal_operation ? '' : 'X'], ['5', '', 'แƒแƒžแƒ”แƒ แƒแƒชแƒ˜แƒ˜แƒก แƒจแƒ˜แƒœแƒแƒแƒ แƒกแƒ˜', 'แƒ’แƒแƒ“แƒแƒ–แƒ˜แƒ“แƒ•แƒ', internal_operation ? 'X' : ''], ['', '', '', 'แƒ“แƒ˜แƒกแƒ แƒ˜แƒ‘แƒฃแƒชแƒ˜แƒ', '']] tbl1 = make_table (items, :column_widths => [15,5]) do column(0).row(0).style(:borders => []) column(0).row(1).style(:background_color => 'eeeeee', :align => :center) column(0).row(2).style(:borders => []) column(1).style(:borders => []) column(2).row(0).style(:borders => [:left, :top]) column(2).row(1).style(:borders => [:left]) column(2).row(2).style(:borders => [:left, :bottom]) end make_table([[tbl1], ['แƒจแƒ”แƒกแƒแƒ‘แƒแƒ›แƒ˜แƒกแƒ˜ แƒฃแƒฏแƒ แƒ แƒแƒฆแƒœแƒ˜แƒจแƒœแƒ”แƒ— X แƒœแƒ˜แƒจแƒœแƒ˜แƒ—']], :cell_style => {:borders => []}) do row(1).style(:align => :center, :size => 5, :padding => 1) end end def waybill_addresses(waybill) items = [ ['6', '', waybill.wb_invoice.sender_address], ['', '', 'แƒขแƒ แƒแƒœแƒกแƒžแƒแƒ แƒขแƒ˜แƒ แƒ”แƒ‘แƒ˜แƒก แƒ“แƒแƒฌแƒงแƒ”แƒ‘แƒ˜แƒก แƒแƒ“แƒ’แƒ˜แƒšแƒ˜ (แƒ›แƒ˜แƒกแƒแƒ›แƒแƒ แƒ—แƒ˜)'], ['7', '', waybill.wb_invoice.receiver_address], ['', '', 'แƒขแƒ แƒแƒœแƒกแƒžแƒแƒ แƒขแƒ˜แƒ แƒ”แƒ‘แƒ˜แƒก แƒ“แƒแƒกแƒ แƒฃแƒšแƒ”แƒ‘แƒ˜แƒก แƒแƒ“แƒ’แƒ˜แƒšแƒ˜ (แƒ›แƒ˜แƒกแƒแƒ›แƒแƒ แƒ—แƒ˜)'] ] make_table items, :column_widths => [15, 5, 380] do column(1).style(:borders => []) column(0).row(0).style(:background_color => 'eeeeee', :align => :center) column(0).row(2).style(:background_color => 'eeeeee', :align => :center) row(1).style(:borders => []) row(3).style(:borders => []) column(2).style(:align => :center) column(2).row(1).style(:padding => 1, :size => 5) column(2).row(3).style(:padding => 1, :size => 5) column(2).row(0).style(:borders => [:bottom], :size => 7) column(2).row(2).style(:borders => [:bottom], :size => 7) end end def print_transport(waybill) def cell8(waybill) trans_number = waybill.wb_invoice.transport_number trans_marka = waybill.wb_invoice.transport_marka if trans_number && trans_marka c8 = "#{trans_number}, #{trans_marka}" else c8 = "#{trans_number}#{trans_marka}" end make_table([['8', ' ', c8],[' ', ' ', 'แƒกแƒแƒขแƒ แƒแƒœแƒกแƒžแƒแƒ แƒขแƒ แƒกแƒแƒจแƒฃแƒแƒšแƒ”แƒ‘แƒ˜แƒก แƒ›แƒแƒ แƒ™แƒ, แƒœแƒแƒ›แƒ”แƒ แƒ˜']], :column_widths => [15, 5, 200]) do column(1).style(:borders => []) row(1).style(:borders => []) row(0).column(0).style(:background_color => 'eeeeee', :align => :center) row(0).column(2).style(:align => :center, :borders => [:bottom], :size => 7) row(1).column(2).style(:align => :center, :padding => 1, :size => 5) end end c8 = cell8(waybill) driver_id = waybill.wb_invoice.driver_id driver_id = ' ' if driver_id == nil or driver_id.empty? c9 = tax_code_box('แƒ›แƒซแƒฆแƒแƒšแƒ˜แƒก แƒžแƒ˜แƒ แƒแƒ“แƒ˜ แƒœแƒแƒ›แƒ”แƒ แƒ˜', '9', driver_id, 100) table([[c8, c9]], :cell_style => {:borders => []}) end def make_horiz_stroke move_down 1 stroke_horizontal_rule move_down 1 end def tax_code_box(title, number, tax_code, caption_width = 80) tax_chars = tax_code ? tax_code.split(//) : [' '] * 11 tax_chars = tax_chars[0..11] if tax_chars.size > 11 items = [[title, number, ''] + tax_chars] widths = [caption_width, 15, 5] + ([12] * tax_chars.size) make_table (items, :cell_style => {:padding => 4, :align => :center}, :column_widths => widths) do column(0).style(:align => :left, :borders => []) column(1).style({:background_color => 'eeeeee'}) column(2).style(:borders => []) end end def p3_width bounds.right - bounds.left - @@wb_part2_width - 5 end def p2_column_widths p2 = @@wb_part2_width w1 = p2 - 53 * 2 - 80; [10, w1, 35, 35, 53, 53] end def p3_column_widths p3 = p3_width w6 = p3 - 45 * 3 [w6, 45, 45, 45] end end
class Student attr_accessor :name, :location, :twitter, :linkedin, :github, :blog, :profile_quote, :bio, :profile_url @@all = [] def initialize(student_hash={}) student_hash.each{|k,v| self.send("#{k}=", v)} @@all << self end def self.create_from_collection(students_array) students_array.collect do |student_array| student = Student.new(student_array) # student.name = students_array[:name] # student.location = students_array[:location] student.twitter = [] student.linkedin = [] student.github = [] student.blog = [] student.profile_quote = [] student.bio = [] student.profile_url = [] end end def add_student_attributes(attributes_hash) attributes_hash.each{|k,v| self.send("#{k}=", v)} end def self.all @@all end end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2014-2022 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo module Protocol # A Hash that caches the results of #to_bson. # # @api private class CachingHash def initialize(hash) @hash = hash end def bson_type Hash::BSON_TYPE end # Caches the result of to_bson and writes it to the given buffer on subsequent # calls to this method. If this method is originally called without validation, # and then is subsequently called with validation, we will want to recalculate # the to_bson to trigger the validations. # # @param [ BSON::ByteBuffer ] buffer The encoded BSON buffer to append to. # @param [ true, false ] validating_keys Whether keys should be validated when serializing. # This option is deprecated and will not be used. It will removed in version 3.0. # # @return [ BSON::ByteBuffer ] The buffer with the encoded object. def to_bson(buffer = BSON::ByteBuffer.new, validating_keys = nil) if !@bytes @bytes = @hash.to_bson(BSON::ByteBuffer.new).to_s end buffer.put_bytes(@bytes) end end end end
#============================================================================== # XaiL System - History Book # Author: Nicke # Created: 31/12/2012 # Edited: 04/01/2013 # Version: 1.0a #============================================================================== # Instructions # ----------------------------------------------------------------------------- # To install this script, open up your script editor and copy/paste this script # to an open slot below ? Materials but above ? Main. Remember to save. #============================================================================== # Requires: XS - Core Script. #============================================================================== # # This script adds a new scene to your game, which can be called by the # following script call: # SceneManager.call_ext(Scene_HistBook, :symbol) # # Example: # SceneManager.call_ext(Scene_HistBook, :ancient_book) # # Basicially you call the scene with the book you want the player to see. # In the above example ancient_book is used. Those books can be edited below # in the settings module. # # Each book can have unlimited pages. # Font and skin settings for the window can be changed. # # *** Only for RPG Maker VX Ace. *** #============================================================================== ($imported ||= {})["XAIL-HISTORY-BOOK"] = true module XAIL module HIST_BOOK #--------------------------------------------------------------------------# # * Settings #--------------------------------------------------------------------------# # FONT: # FONT = [name, size, color, bold, shadow] FONT = [["Calibri", "Verdana"], 18, Color.new(255,255,255), true, true] # Setup the books. # :title => [page1, page2, page3...] # In the array for pages you can use the following to output a string: # %{Some text}, "Some text" etc. # The title will be converted, capitalized and any underlines will # be removed. #--------------------------------------------------------------------------# BOOKS = { 0 => [%{Please select a valid book to read if you want OWO }], #Welcome to Equestria 301 => [%{ Equestria is the main setting of the My Little Pony Friendship is Magic franchise. Equestria is inhabited by magical ponies and other talking creatures, such as griffons and dragons. Other animals and creatures also live in Equestria. Equestria is called a kingdom on the first episode of the show and in other media, though it does contain other "kingdoms" within it such as the Crystal Empire or Crystal Kingdom; the show and other media take place in many locations and their exact affiliation with Equestria is not explored. Equestria is co-ruled by Princess Celestia and Princess Luna, who reside in a palace in the city of Canterlot. The name "Equestria" is derived from the word "equestrian" (which means of or related to horseback riding), which stems from equus, the Latin word for "horse.". }, #Blank line: 63 %{ The founding of Equestria: The story of the founding of Equestria is relayed in software, and part of this explanation is covered in Hearth's Warming Eve. The episode's most prominent feature is a play about the founding of Equestria, narrated by Spike. He explains: "each of the three tribes, the Pegasi, the unicorns, and the Earth ponies, cared not for what befell the other tribes, but only for their own welfare. In those troubled times, as now, the Pegasi were the stewards of the weather, but they demanded something in return: food that could only be grown by the Earth Ponies. The unicorns demanded the same, in return for magically bringing forth day and night. And so, mistrust between the tribes festered, until one fateful day, it came to a boil. And what prompted the ponies to clash? It was a mysterious blizzard that overtook the land, and toppled the tribes' precarious peace." }, %{ The blizzard led to famine, at which the three tribal leaders eventually agreed to meet for a summit and decide what to do about the snow, but this only devolved into arguing and blaming each other. The leaders of each tribe then decided to journey to a new land. They all arrived at the same place, and soon began fighting over it, and the blizzard quickly followed. "And so the paradise that the ponies had found was soon lost, buried beneath a thick blanket of snow and hard feelings." Eventually, the leaders' assistants find out windigos are causing the storm by feeding off of hate. The assistants' friendship creates the magical Fire of Friendship which does away with the windigos and the snowstorm. The three leaders then decide to join forces and found a country shared by all three tribes, and name it Equestria. }, %{Discord's reign of chaos: The series starts off with a prologue with narration about the princesses ruling Equestria, raising the sun and moon and maintaining harmony. Only in The Return of Harmony Part 1 is the time before their rule mentioned in the series. Princess Celestia tells Twilight Sparkle and her friends that before Princess Luna and herself stood up to Discord, he ruled over Equestria, keeping it in a state of unrest and unhappiness. Celestia goes on to describe that, seeing how miserable life was for Earth ponies, unicorns, and Pegasi alike, she and Luna discovered the Elements of Harmony and rose up against Discord, turning him to stone. Discord's spell is later broken because, as Celestia explains, "Luna and [herself] are no longer connected to the elements", so Twilight and her friends use the Elements of Harmony to encase Discord in stone again. }, %{ The regal Alicorn sisters The princesses are introduced in the prologue of the first episode, depicted in a series of medieval-like drawings with a narration that says "two regal sisters who ruled together and created harmony for all the land", and that "the eldest used her unicorn powers to raise the sun at dawn. The younger brought out the moon to begin the night." }, %{Nightmare Moon : The narration continues: their subjects, the ponies, played in the day but "shunned" the night and slept through it, which made the younger unicorn grow bitter, eventually refusing to lower the moon to make way for the dawn. Her bitterness transformed her into a "wicked mare of darkness", Nightmare Moon. The elder sister reluctantly harnessed the power of the Elements of Harmony and banished her in the moon, taking responsibility for both sun and moon, maintaining harmony in Equestria. The events of the first and second episodes take place a thousand years after Nightmare Moon's imprisonment, upon which she is freed, but defeated again through the magic of the Elements of Harmony, only this time she is transformed back to her former self and returns to rule Equestria with her sister. In Testing Testing 1, 2, 3, these events are referred to as "The Great Celestia/Luna Rift." }, ], #Elements of Harmony 302 => [%{Elements of Harmony are six mystical jewels that harness the power of friendship. Little is known about the enigmatic Elements, but they're extremely powerful and can only be used in unison. }, %{Their mysterious origins are tied to Equestria's distant past, a time when two Alicorn Sisters, Princess Celestia and Princess Luna, used their magical power to rule the lands. Celestia raised the sun, and Luna raised roused the moon in the evening. As time went on, Luna grew frustrated watching ponies play all day and sleep during the night. She felt her fard work was going unnoticed, and her seething anger and jealous grew until they transformed the otherwise pleasant pony into the vengeful Nightmare Moon. Using her newfound abilities, Nightmare Moon plunged Equestria into drakness. Thankfully, Princess Celestia was able to harness the power of the Elements of Harmony to stop her sister and exile her into the moon for all eternity. Balance has returned to Equestria, but Celestia knew that peace woundn't last forever.}, %{In the present, young Twilight Sparkle discovered a dark prophecy that heralded the return of Nightmare Moon on the longest day of the thousand year. She desperately contacted Princess Celestia to warn her of of the impending danger, but the princess dismissed Twilight's concern and insisted she focus her attention on the upcoming Summer Sun Celebration. Princess Celestia was convinced that the celebration would yield Twilight a number of new friends, and it certainly did.}, %{During the event, Twilight Sparkle instantly found five new pony pals: Fluttershy, Pinkie Pie, Rainbowdash , Applejack and Rarity. It seemed, at first, that prophecy was untrue, until suddenly Princess Celestia disappeared and Nightmare Moon once again bought the darkness to Equestria.}, %{Twilight quickly realized that there was only way to save the day. She and her new friends had to find and retrieve the mystical Elements of Harmony from ancient castle of the royal pony sisters! They traveled through the dangerous Everfree Forest and, after a perilous jounary, finally arrived at the castle. During their quest, the new pony friends confronted a myriad of dangers that brought them closer together in process. Upon finding the Elements, the group was ambushed by Nightmare Moon, who seemingly destroyed the precious stone and doomed Equestria forever.}, %{ But Twilight Sparkle realized that hope wasn't lost and that her new friends were the key to defeating Nightmare moon. They each embodied the various aspects if the Elements of Harmony,and by working together, they pooled their power and used it against the vengeful Alicorn.}, %{As Twilight called out the names of her friends, the broken Elements re-formed into sparkling new pendants that gave each other of their new owner a power of friendship! Applejack represented Honesty, Fluttershy embodied the spirit of Kindness, Pinkie Pie brought the group laughter, Rarity exuded Generosity, and Rainbow Dash's strong suit was Loyalty. Twilight Sparkle empbodied the Element of Magic, which only sparked when all the other Elements were presented, Together, the ponies ised their newfound powers to transform Nightmare Moon back into the benevolent form of Princess Luna, once again bringing light to Equestria.}, %{With the kingdom now safe, Princess Celestia revealed that she knew Twilight Sparkle would be able to save the day by harnessung the power of Elements, The princess then gave Twilight a special mission to chronicle the magic of friendship and report on the valuable lessons she learned. Over time, the Elements of Harmony have been used sparingly, in times of of dire necessity, and never in a harmful or hurtful way. When trouble arises, the duty falls to those six brave ponies to bring peace and order to Equestria once again.}, ], #Star Doom 303 => [ %{Anti-Magi Sword, Star Doom. Star Swirl the Bearded , one of the famous unicorn in the history of Equestria , invneted several high-level spells supported Celestia to rule the Equestria. Meanwhile, the class of Unicorn had gradually higher than Pegasus and Earth-Pony. The radicals of the two latters got very uncomfortable , worried the cold war in the three-trible era happened again, secretly sneak to Crystal Mountain mined the Mithril, Orichalcon, Hihi'irokane etc. magical metal, forged this deadly weapon. The Legend says, the victims under its blade, they will not be able to cast spells for days.}, %{Ability : Owner Reflect Magic, ATK:200 , -100 MAT, -200 MP}, ], #Crystal Portal Coded Document 304 =>[ #%{ไธ€ไบŒไธ‰ๅ››ไบ”ไธƒๅ…ซไน้›ถไธ€ไบŒไธ‰ๅ››ไบ”ไธƒๅ…ซไน้›ถไธ€ไบŒไธ‰ๅ››ไบ”ไธƒๅ…ซไน้›ถไธ€ไบŒไธ‰}, %{ไปŠๅ‚ณ้€้–€ไน‹ๆ€ง่ƒฝไป็‚บไน‹ไธๅฎš๏ผŒ็‚บๆฑ‚ๅฎ‰ๅ…จ๏ผŒๆ•…ๅŠ ๅฏ†ไน‹ใ€‚ \nๆฌฒไฝฟ็”จ่€…๏ผŒ่งฃไธ‹10้กŒ้ธๆ“‡้กŒไน‹็ญ”ๆกˆ็‚บๆญฃ็ขบไน‹10ไฝๆ•ธๅฏ†็ขผใ€‚\n ๅ…ถๆฏ้กŒ็ญ”ๆกˆ้ƒฝไธ่ƒฝ่‡ช็›ธ็Ÿ›็›พใ€‚}, %{(1)็ฌฌไธ€ๅ€‹็ญ”ๆกˆๆ˜ฏB็š„้กŒ่™Ÿๆ˜ฏ็ฌฌๅนพ้กŒ? (A)2 (B)3 (C)4 (D)5 (E)6 \n(2)ๆฐๅฅฝๆœ‰ๅ…ฉๅ€‹้€ฃ็บŒๅ•้กŒ็š„็ญ”ๆกˆๆ˜ฏไธ€ๆจฃ็š„๏ผŒ้กŒ่™Ÿๆ˜ฏ: \n (A)2,3 (B)3,4 (C)4,5 (D)5,6 (E)6,7 \n (3)ๆœฌ้กŒ็š„็ญ”ๆกˆๅ’Œๅ“ชไธ€้กŒ็ญ”ๆกˆไธ€ๆจฃ? \n(A)1 (B)2 (C)4 (D)7 (E)6 \n(4)็ญ”ๆกˆๆ˜ฏA็š„ๅ•้กŒๅ€‹ๆ•ธๆ˜ฏ: \n (A)0 (B)1 (C)2 (D)3 (E)4 \n(5)ๆœฌ้กŒ็ญ”ๆกˆๅ’Œ็ฌฌๅนพ้กŒ็›ธๅŒ? (A)10 (B)9 (C)8 (D)7 (E)6 \n(6)็ญ”ๆกˆๆ˜ฏA็š„ๅ•้กŒๅ€‹ๆ•ธๅ’Œ็ญ”ๆกˆ็‚บๅคšๅฐ‘็š„ๅ€‹ๆ•ธไธ€ๆจฃ? \n (A)B (B)C (C)D (D)E (E)ไปฅไธŠ็š†้ž \n (7)ๆŒ‰็…งๅญ—ๆฏ้ †ๅบ๏ผŒๆœฌๅ•้กŒ็š„็ญ”ๆกˆๅ’Œไธ‹ไธ€ๅ€‹ๅ•้กŒ็š„็ญ”ๆกˆ็›ธๅทฎๅนพๅ€‹ๅญ—ๆฏ? \n (A)4 (B)3 (C)2 (D)1 (E)0 \n}, %{(8)็ญ”ๆกˆๆ˜ฏๆฏ้Ÿณๅญ—ๆฏ็š„ๅ•้กŒๅ€‹ๆ•ธๆ˜ฏ: (A)2 (B)3 (C)4 (D)5 (E)6 \n(9)็ญ”ๆกˆๆ˜ฏๅญ้Ÿณๅญ—ๆฏ็š„ๅ€‹ๆ•ธๆ˜ฏ: \n (A)ไธ€ๅ€‹่ณชๆ•ธ (B)ไธ€ๅ€‹้šŽไน˜ๆ•ธ (C)ไธ€ๅ€‹ๅนณๆ–นๆ•ธ (D)ไธ€ๅ€‹ๆข…ๆฃฎ่ณชๆ•ธ (E)5็š„ๅ€ๆ•ธ \n(10)้€™้กŒ็š„็ญ”ๆกˆๆ˜ฏ: (A)A (B)B (C)C (D)D (E)E \n \n ๆ็คบ:็ฌฌไธ€้กŒ็ญ”ๆกˆๆœ‰ๅฏ่ƒฝๆ˜ฏ(B)ๅ—Ž?}, ], } # Don't remove this line! #--------------------------------------------------------------------------# # Change page text. # PAGE_TEXT = string PAGE_TEXT = "Change page with Left/Right buttons." # Single page text. # SINGLE_TEXT = string SINGLE_TEXT = "" # Use default background. (snapshot of the map) # BACK = true/false BACK = true # Custom background. # CUST_BACK = [filename, hide_window] # Optional to use, set filename to "" to disable. CUST_BACK = ["", false] # SKIN: # The windowskin to use for the windows. # Set to nil to disable. # SKIN = string SKIN = nil end end # *** Don't edit below unless you know what you are doing. *** #==============================================================================# # ** Error Handler #==============================================================================# unless $imported["XAIL-XS-CORE"] # // Error handler when XS - Core is not installed. msg = "The script %s requires the latest version of XS - Core in order to function properly." name = "XS - History Book" msgbox(sprintf(msg, name)) exit end #==============================================================================# # ** Window_HistoryBook #==============================================================================# class Window_HistoryBook < Window_Command def initialize(x, y) # // Method to initialize the window. super(x, y) @page = 1 end def window_width # // Method to return the width. return Graphics.width end def window_height # // Method to return the height. return Graphics.height end def set_book(book) # // Method to set book. if book != @book @book = book refresh end end def change_page(page) # // Method to change page. if page != @page @page = page refresh end end def refresh # // Method to refresh the window. super contents.clear unless @book.nil? draw_book draw_details end end def draw_book book_title = ["History of Equestria","Elements of Harmony","Star Doom","ๆฐดๆ™ถๅ‚ณ้€้–€ๅŠ ๅฏ†ๆ–‡ไปถ",""] # // Method to draw the tp text to the window. title = @book.to_s.slice_char("_").cap_words text = XAIL::HIST_BOOK::BOOKS[@book][@page - 1] # // Title. if title[0].to_s >= '3' then title = book_title[title.to_i - 301] elsif title[0] == '0' then title = " I just don't know what went wrong O_O" end draw_font_text(title, 0, 0, contents_width, 1, XAIL::HIST_BOOK::FONT[0], 30, XAIL::HIST_BOOK::FONT[2]) # // Line. draw_line_ex(0,44, Color.new(255,255,255), Color.new(0,0,0)) # // Book text. draw_font_text_ex(text, 0, 72, XAIL::HIST_BOOK::FONT[0], XAIL::HIST_BOOK::FONT[1], XAIL::HIST_BOOK::FONT[2]) end def draw_details # // Method to draw details. current_page = @page.to_s max_page = XAIL::HIST_BOOK::BOOKS[@book].size.to_s page = "Page: " + current_page + " / " + max_page # // Line. draw_line_ex(0, contents_height - 36, Color.new(255,255,255), Color.new(0,0,0)) if XAIL::HIST_BOOK::BOOKS[@book].size > 1 # // Change page text. page_text = XAIL::HIST_BOOK::PAGE_TEXT draw_font_text(page_text, 0, contents_height - calc_line_height(page_text), contents_width, 0, XAIL::HIST_BOOK::FONT[0], 20, XAIL::HIST_BOOK::FONT[2]) # // Current page and max page. draw_font_text(page, 0, contents_height - calc_line_height(page), contents_width, 2, XAIL::HIST_BOOK::FONT[0], 20, XAIL::HIST_BOOK::FONT[2]) else # // Single page text. single_text = XAIL::HIST_BOOK::SINGLE_TEXT draw_font_text(single_text, 0, contents_height - calc_line_height(single_text), contents_width, 0, XAIL::HIST_BOOK::FONT[0], 20, XAIL::HIST_BOOK::FONT[2]) end end end #==============================================================================# # ** Scene_HistBook #==============================================================================# class Scene_HistBook < Scene_Base def initialize(book = nil) # // Method to initialize the scene. super @book = book end def start # // Method to start the scene. super @page = 1 create_history_window create_background if XAIL::HIST_BOOK::BACK create_custom_background unless XAIL::HIST_BOOK::CUST_BACK[0] == "" end def create_background # // Method to create a background. @background_sprite = Sprite.new @background_sprite.bitmap = SceneManager.background_bitmap @background_sprite.color.set(16, 16, 16, 128) end def create_custom_background # // Method to create a custom background. begin @custom_background = Sprite.new @custom_background.bitmap = Cache.picture(XAIL::HIST_BOOK::CUST_BACK[0]) rescue msgbox("Error! Unable to locate the custom background: " + XAIL::HIST_BOOK::CUST_BACK[0]) exit end end def valid_book? # // Method to check if book is valid. (included in book list) # // Return (skip it) if included else show error. return if XAIL::HIST_BOOK::BOOKS.include?(@book) #msgbox("Error! The book " + @book.to_s + " is not added in the list.") @book = 0 end def create_history_window # // Method to create command list window. # // Check first if book is a valid one, i.e it is added in the book list. valid_book? @history_window = Window_HistoryBook.new(0, 0) @history_window.opacity = 0 if XAIL::HIST_BOOK::CUST_BACK[1] @history_window.windowskin = Cache.system(XAIL::HIST_BOOK::SKIN) unless XAIL::HIST_BOOK::SKIN.nil? # // Add page left/right methods if a book have more then one page. if XAIL::HIST_BOOK::BOOKS[@book].size > 1 @history_window.set_handler(:pageright, method(:next_page)) @history_window.set_handler(:pageleft, method(:prev_page)) end @history_window.set_handler(:cancel, method(:return_scene)) @history_window.set_book(@book) @history_window.unselect end def next_page Audio.se_stop # // Method to select next page. @page += 1 unless @page == XAIL::HIST_BOOK::BOOKS[@book].size Audio.se_play("Audio/SE/Book2",80, 100) @history_window.activate @history_window.change_page(@page) end def prev_page Audio.se_stop # // Method to select previous page. @page -= 1 unless @page == 1 Audio.se_play("Audio/SE/Book2",80, 100) @history_window.activate @history_window.change_page(@page) end end # END OF FILE #=*==========================================================================*=# # ** END OF FILE #=*==========================================================================*=#
class HomeController < ApplicationController layout 'home' def index @blogs = Blog.where(:publish => true).order("created_at desc").paginate(:page => params[:page], :per_page => 10) end def show @blog = Blog.find(params[:id]) # get all current user friends @friends = current_user.friendships.where(:status => true).map { |friendship| friendship.friend} @friends << current_user.inverse_friendships.where(:status => true).map { |friendship| friendship.user} @friends = @friends.flatten end end
# -*- mode: ruby -*- # vi: set ft=ruby : # All Vagrant configuration is done below. The "2" in Vagrant.configure # configures the configuration version (we support older styles for # backwards compatibility). Please don't change it unless you know what # you're doing. Vagrant.configure("2") do |config| # The most common configuration options are documented and commented below. # For a complete reference, please see the online documentation at # https://docs.vagrantup.com. # Every Vagrant development environment requires a box. You can search for # boxes at https://atlas.hashicorp.com/search. config.vm.box = "ubuntu/trusty64" # Disable automatic box update checking. If you disable this, then # boxes will only be checked for updates when the user runs # `vagrant box outdated`. This is not recommended. # config.vm.box_check_update = false # Create a forwarded port mapping which allows access to a specific port # within the machine from a port on the host machine. In the example below, # accessing "localhost:8080" will access port 80 on the guest machine. # config.vm.network "forwarded_port", guest: 80, host: 8080 # Create a private network, which allows host-only access to the machine # using a specific IP. config.vm.network "private_network", ip: "192.168.33.10" # Create a public network, which generally matched to bridged network. # Bridged networks make the machine appear as another physical device on # your network. # config.vm.network "public_network" # Share an additional folder to the guest VM. The first argument is # the path on the host to the actual folder. The second argument is # the path on the guest to mount the folder. And the optional third # argument is a set of non-required options. config.vm.synced_folder "../", "/gtree" # Provider-specific configuration so you can fine-tune various # backing providers for Vagrant. These expose provider-specific options. # Example for VirtualBox: # config.vm.provider "virtualbox" do |vb| # Display the VirtualBox GUI when booting the machine # vb.gui = true # Customize the amount of memory on the VM: vb.memory = "1024" # Set the name vb.name = "gtree" end # # View the documentation for the provider you are using for more # information on available options. # Define a Vagrant Push strategy for pushing to Atlas. Other push strategies # such as FTP and Heroku are also available. See the documentation at # https://docs.vagrantup.com/v2/push/atlas.html for more information. # config.push.define "atlas" do |push| # push.app = "YOUR_ATLAS_USERNAME/YOUR_APPLICATION_NAME" # end # Enable provisioning with a shell script. Additional provisioners such as # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the # documentation for more information about their specific syntax and use. config.vm.provision "shell", inline: <<-SHELL apt-get update # install general dev dependencies apt-get install -y git vim python apt-get install -y unzip # install pIRS dependencies apt-get install -y libboost-all-dev zlib1g-dev build-essential apt-get install -y libwxgtk2.8-dev libpango1.0-dev libreadline5-dev libx11-dev libxt-dev texinfo libgd2-xpm-dev gnuplot gzip # install pIRS git clone https://github.com/galaxy001/pirs.git cd pirs; make; find . -type l | \ while read a; do cp --copy-contents -LR "$a" /usr/local/bin/; done; # install genomics toolkits apt-get install -y samtools # install BWA cd $HOME curl -OL http://downloads.sourceforge.net/project/bio-bwa/bwa-0.7.12.tar.bz2 tar -xvf bwa-0.7.12.tar.bz2 cd bwa-0.7.12; make; cp ./bwa /usr/local/bin/ # install bowtie cd $HOME curl -OL http://downloads.sourceforge.net/project/bowtie-bio/bowtie/1.1.2/bowtie-1.1.2-linux-x86_64.zip unzip bowtie-1.1.2-linux-x86_64.zip cd bowtie-1.1.2; cp bowtie* /usr/local/bin/ # install bowtie2 cd $HOME curl -OL http://downloads.sourceforge.net/project/bowtie-bio/bowtie2/2.2.9/bowtie2-2.2.9-linux-x86_64.zip unzip bowtie2-2.2.9-linux-x86_64.zip cd bowtie2-2.2.9; cp bowtie2* /usr/local/bin/ # system should now be built and configured with the biggest # aligners installed to test and profile against! # SHELL end
require "test_helper" feature "Change email Feature Test" do background do @user = FactoryGirl.create(:user, email: "jim.bobby@gmail.com", name: "Jimbob McBobsalot") login_as(@user) visit dashboard_path current_path.must_equal dashboard_path click_link "settings" current_path.must_equal "/users/edit" fill_in "Password", with: "newpass" fill_in "Password confirmation", with: "newpass" end scenario "without current password" do fill_in "Current password", with: "wrongpass" click_button "Update" page.must_have_selector(".alert", text: /Please review the problems below/) current_path.must_equal "/users" end scenario "with current password" do fill_in "Current password", with: @user.password click_button "Update" page.assert_selector("#flash_notice", text: /updated successfully./) current_path.must_equal "/dashboard" end end
class UsersController < ApplicationController before_filter :require_login, :except => [:create, :new] def index if current_user if current_user.gender == ("M" || "m") gender = "F" || "f" else gender = "M" || "m" end end query = params[:query] if query.blank? @users = User.where(:gender => gender) else search = User.search { fulltext query } @users = search.results end end def find_picture user = User.find(params[:id]) index = params[:index] index = index.to_i render json: user.photos[index].picture end def show @user = User.find(params[:id]) @photo = Photo.new end def create @user = User.new(params[:user]) if @user.save auto_login(@user) if params[:stripeToken] != nil customer = Stripe::Customer.create( :email => @user.email, :card => params[:stripeToken], :plan => "paid" ) end redirect_to user_url(@user) else render :new end end def update @user = current_user respond_to do |format| if @user.update_attributes(params[:user]) @user.photos.each do |photo| photo.update_attributes(:is_profile => false) end @user.photos.find(params[:photo_id]).update_attributes(:is_profile => true) format.html { redirect_to @user, notice: 'Just saved your new profile :)' } else format.html { render action: "edit" } end end end def destroy end def match end def new @user = User.new end def edit @user = current_user end end
Rails.application.routes.draw do root to: 'pages#home' get 'contact', to: 'pages#contact' get '/*all', to: 'pages#missing' end
# frozen_string_literal: true require 'test_helper' class ProgImagesControllerTest < ActionDispatch::IntegrationTest setup do @prog_image = prog_images(:one) end test 'should get index' do get prog_images_url, as: :json assert_response :success end test 'should create prog_image' do assert_difference('ProgImage.count') do post prog_images_url, params: { prog_image: {} }, as: :json end assert_response 201 end test 'should show prog_image' do get prog_image_url(@prog_image), as: :json assert_response :success end test 'should update prog_image' do patch prog_image_url(@prog_image), params: { prog_image: {} }, as: :json assert_response 200 end test 'should destroy prog_image' do assert_difference('ProgImage.count', -1) do delete prog_image_url(@prog_image), as: :json end assert_response 204 end end
module CapsuleCD module RSpecSupport module PackageTypes def package_types Dir.entries('lib/capsulecd').select {|entry| File.directory? File.join('lib/capsulecd',entry) and !(entry =='.' || entry == '..' || entry == 'base') } end end end end
require 'spec_helper' require 'database_cleaner' DatabaseCleaner.strategy = :truncation feature "the signup process" do it "has a new user page" do visit new_user_url expect(page).to have_content "Sign Up" end feature "signing up a user" do it "shows username on the homepage after signup" do visit new_user_url fill_in 'Username', :with => "jonathan" fill_in 'Password', :with => "sennacy" click_on "Sign Up" end end feature "user uses invalid credential" do #user = FactoryGirl.build(:user, :username => "", :password => "" ) before(:each) do visit new_user_url fill_in 'Username', :with => "" fill_in 'Password', :with => "" click_on "Submit" end it "shouldn't let username be blank" do expect(page).to have_content "Username can't be blank" end it "shouldn't let password be less than 6 characters" do expect(page).to have_content "Password is too short" end it "should rerender page" do expect(page).to have_content "Sign Up" end end end feature "logging in" do DatabaseCleaner.clean user = FactoryGirl.build(:user) user.save! before(:each) do visit new_session_url fill_in 'Username', :with => user.username fill_in 'Password', :with => user.password click_on "Submit" end it "shows username on the homepage after login" do visit new_session_url fill_in 'Username', :with => user.username fill_in 'Password', :with => user.password click_on "Submit" expect(page).to have_content "andrew" end end feature "logging out" do DatabaseCleaner.clean user = FactoryGirl.build(:user) user.save! it "begins with logged out state" do visit root_url expect(page).to have_content("Sign In") end it "doesn't show username on the homepage after logout" do visit new_session_url fill_in 'Username', :with => user.username fill_in 'Password', :with => user.password click_on "Submit" click_on "Sign Out" expect(page).not_to have_content(user.username) end end
class ApplicationController < ActionController::Base protect_from_forgery def authenticate_active_admin_user! authenticate_user! redirect_to root_path, alert: 'Unauthorized Access!' unless current_user.admin? end end
class Book @@on_shelf=[] @@on_loan=[] def initialize(title, author, isbn) @title=title @author=author @isbn=isbn end def due_date return @due_date end def due_date=(due_date) @due_date=due_date end def borrow if lend_out? == false @due_date=Book.current_due_date loaning=@@on_shelf.delete(self)############################ help me @@on_loan.push(loaning) return true else return false end end def return_to_library if lend_out? @due_date= nil depositing=@@on_loan.delete(self)############################ help me @@on_shelf.push(depositing) return true else return false end end def lend_out? if @@on_shelf.include?(self) return false else return true end end def isbn return @isbn end def self.create(author, title, isbn) book_add = Book.new(author, title, isbn) @@on_shelf.push(book_add) return book_add end def self.current_due_date return Time.now+(60*60*24*7) end def self.overdue_books @@on_loan.each do |bookOBJ| if bookOBJ.due_date < Time.now return bookOBJ end end end def self.browse return @@on_shelf.sample end def self.available return @@on_shelf end def borrowed return @@on_loan end end newbook=Book.create("Sister Outsider", "Audre Lorde", "9781515905431") p newbook newbook2=Book.create("Ain't I a Woman", "Bell Hooks", "9780896081307") p newbook2 newbook3=Book.create("If They Come in the Morning", "Angela Y. Davis", "0893880221") p newbook3 puts p Book.available #list all available books in library puts p newbook2.borrowed#returns all the books that were borrowed aka not in library puts p Book.browse#list random book in library puts p newbook3.lend_out? #returns true if the books is not in library false if it is in library puts p newbook3.borrow#borrow book3 puts p newbook3.lend_out? puts # p Book.current_due_date # puts # p newbook3.borrow # puts # p newbook3.borrow # puts p newbook3.due_date puts p newbook3.borrowed puts # p newbook3.return_to_library # puts # p newbook3.return_to_library # puts p Book.overdue_books puts
class Capybara::Driver::Base def browser_initialized? true end end
class AddNotations < ActiveRecord::Migration[4.2] def change create_table :notations do |t| t.integer 'concept_id' t.string 'value', limit: 4000 t.string 'data_type', limit: 4000 end end end
class Help include BotPlugin def initialize(muc, plugins) super(muc, plugins) end def process(time, nick, command) return false unless (command =~ /^help$/ or command =~ /^help /) if command =~ /^help$/ # we want a listing helps = @plugin_instances.inject([]) { |helps, p| helps << p.help_list(time, nick) } @muc.say("#{nick}: #{helps.compact.join("\n")}") elsif msg = command =~ /^help (.*)/ && $1 #we want a specific help found = @plugin_instances.inject(false) { |found, p| p.help(time, nick, msg) || found } @muc.say("#{nick}: no such command") unless found else return false end return true end def help_list(time, nick) return "help [topic]" end def help(time, nick, command) return false unless command =~ /^help$/ @muc.say("#{nick}: help [topic]\nGet information on bot commands.") return true end end
require 'spec_helper' describe user('zabbix') do it { should exist } it { should belong_to_group 'zabbix' } end %w(zabbix-release zabbix-server-pgsql zabbix-web-pgsql zabbix-web zabbix-web-japanese zabbix zabbix-get).each do |pkg| describe package(pkg) do it { should be_installed } end end describe file('/etc/zabbix/zabbix_server.conf') do it { should be_file } end describe service('zabbix-server') do it { should be_enabled } it { should be_running } end describe port(10051) do it { should be_listening } end
# https://leetcode.com/explore/featured/card/july-leetcoding-challenge/544/week-1-july-1st-july-7th/3377/ # @param {Integer} n # @return {Integer} def arrange_coins(n) x = (Math.sqrt(2 * n)).floor if x * (x + 1) > 2 * n return x - 1 else return x end end puts arrange_coins(8) =begin general strategy for given n, we need to find lower bound of the number 1+2+...+x = n x * (x+1) = 2 * n x = floor(sqrt(2 * n)) then if x * (x+1) > 2 * n return x - 1 else if x * (x + 1) <= 2 * n return x =end
class InquiriesController < ApplicationController def new @inquiry = Inquiry.new end def create @inquiry = Inquiry.new(inquiry_params) if @inquiry.save NotificationMailer.send_notification(@inquiry).deliver # redirect_to inquiries_thank_path(id:@inquiry.id) render 'thank' # @test = Writespread.new # @test.test(@inquiry[:email]) else render 'new' end end def thank @inquiry = Inquiry.find(params[:id]) end private def inquiry_params params.require(:inquiry).permit(:name, :email, :tel, :servicecategories) end end
class Person def initialize(name) @name = name end def greet(other_name) puts "Hi #{other_name}, my name is #{@name}" end end person = Person.new("Saroar") person.greet("Alif")
class CreateProducts < ActiveRecord::Migration def change create_table :products do |t| t.string :name t.string :price t.text :model t.string :asin t.string :mrp t.string :sale t.text :link t.text :source t.timestamps null: false end end end
require 'econfig' require 'sinatra' # API of Backup File System class FileSystemSyncAPI < Sinatra::Base extend Econfig::Shortcut configure do enable :logging Econfig.env = settings.environment.to_s Econfig.root = File.expand_path('..', settings.root) SecureDB.setup(settings.config.DB_KEY) AuthToken.setup(settings.config.DB_KEY) end def authenticated_account(env) begin scheme, auth_token = env['HTTP_AUTHORIZATION'].split(' ') return nil unless scheme.match?(/^Bearer$/i) account_payload = AuthToken.payload(auth_token) Account[account_payload['id']] rescue nil end end def authorized_account?(env, id) account = authenticated_account(env) account.id.to_s == id.to_s rescue false end def _403_if_not_logged_in(account) if account.nil? logger.info "User should log in first." halt 403 end end get '/?' do 'File System Synchronization web API' end end
class ManageIQ::Providers::Amazon::Inventory::Parser::StorageManager::Ebs < ManageIQ::Providers::Amazon::Inventory::Parser def parse log_header = "MIQ(#{self.class.name}.#{__method__}) Collecting data for EMS name: [#{collector.manager.name}] id: [#{collector.manager.id}]" $aws_log.info("#{log_header}...}") volumes snapshots $aws_log.info("#{log_header}...Complete") end private def volumes collector.cloud_volumes.each do |volume| persister_volume = persister.cloud_volumes.find_or_build(volume['volume_id']).assign_attributes( :name => get_from_tags(volume, :name) || volume['volume_id'], :status => volume['state'], :creation_time => volume['create_time'], :volume_type => volume['volume_type'], :size => volume['size'].to_i.gigabytes, :base_snapshot => persister.cloud_volume_snapshots.lazy_find(volume['snapshot_id']), :availability_zone => persister.availability_zones.lazy_find(volume['availability_zone']), :iops => volume['iops'], :encrypted => volume['encrypted'], ) volume_attachments(persister_volume, volume['attachments']) end end def snapshots collector.cloud_volume_snapshots.each do |snap| persister.cloud_volume_snapshots.find_or_build(snap['snapshot_id']).assign_attributes( :name => get_from_tags(snap, :name) || snap['snapshot_id'], :status => snap['state'], :creation_time => snap['start_time'], :description => snap['description'], :size => snap['volume_size'].to_i.gigabytes, :cloud_volume => persister.cloud_volumes.lazy_find(snap['volume_id']), :encrypted => snap['encrypted'], ) end end def volume_attachments(persister_volume, attachments) (attachments || []).each do |a| if a['device'].blank? log_header = "MIQ(#{self.class.name}.#{__method__}) Collecting data for EMS name: [#{collector.manager.name}] id: [#{collector.manager.id}]" $aws_log.warn "#{log_header}: Volume: #{persister_volume.ems_ref}, is missing a mountpoint, skipping the volume processing" $aws_log.warn "#{log_header}: EMS: #{collector.manager.name}, Instance: #{a['instance_id']}" next end dev = File.basename(a['device']) persister.disks.find_or_build_by( :hardware => persister.hardwares.lazy_find(persister.vms.lazy_find(a["instance_id"])), :device_name => dev ).assign_attributes( :location => dev, :size => persister_volume.size, :backing => persister_volume, ) end end end
require 'rails_helper' RSpec.describe UpdateOrganizationJob, type: :job do let(:organization) { Organization.new(facebook_id: 'facebook id') } let(:graph) { double(:get_object => {}, :get_picture_data => {}) } before { allow(Givdo::Facebook).to receive(:graph).and_return(graph) } describe 'facebook error' do let(:error) { Koala::Facebook::ClientError.new(nil, nil) } before { allow(graph).to receive(:get_object).and_raise error } it 'logs and ignore the error' do expect(subject.logger).to receive(:error).with(error) subject.perform(organization) end end describe "organization data update" do let(:facebook_data) do { 'name' => 'Rainforest Foundation', 'mission' => 'Save the rainforest' } end before { allow(graph).to receive(:get_object).with('facebook id', fields: [:mission, :location, :name]).and_return(facebook_data) } it 'saves the cached organization' do subject.perform(organization) expect(organization).to be_persisted expect(organization).to be_cached end it 'saves the organization info' do subject.perform(organization) expect(organization.name).to eql 'Rainforest Foundation' expect(organization.mission).to eql 'Save the rainforest' end context 'when it has location data' do it 'saves it' do facebook_data['location'] = { 'city' => 'Brooklyn', 'state' => 'NY', 'zip' => '11238' } subject.perform(organization) expect(organization.city).to eql 'Brooklyn' expect(organization.state).to eql 'NY' expect(organization.zip).to eql '11238' end end context 'when it does not have location data' do it 'ignores it' do facebook_data.delete('location') organization.zip = '42420' organization.city = 'Old City' organization.state = 'OS' subject.perform(organization) expect(organization.zip).to eql '42420' expect(organization.city).to eql 'Old City' expect(organization.state).to eql 'OS' end end end it 'updates the organization picture' do allow(Givdo::Facebook.graph).to receive(:get_picture_data).with('facebook id', {type: 'large'}).and_return({ 'url' => 'image url' }) subject.perform(organization) expect(organization.picture).to eql 'image url' end end
class CreateMagazines < ActiveRecord::Migration def change create_table :magazines do |t| t.string :title t.string :cover t.string :folder t.string :zip t.datetime :created_at end end end
# encoding: UTF-8 class ProfileMailer < ActionMailer::Base RECIPIENT = ['hello@jerevedunemaison.com', 'tukan2can@gmail.com'] default from: "Je Rรชve dโ€™une Maison <contact@jerevedunemaison.com>" helper :application # gives access to all helpers defined within `application_helper`. def update_mail(profile, user) @profile = profile @user = user attachments.inline['logo.png'] = Rails.root.join('app/assets/images/logo_full.png').read mail(to: RECIPIENT, subject: "Profile updated") do |format| format.html end end end
# Feature: Sign up # As a visitor # I want to sign up # So I can visit protected areas of the site feature 'Sign Up', :devise do # Scenario: Visitor can sign up with valid email address and password # Given I am not signed in # When I sign up with a valid email address and password # Then I see a successful sign up message scenario 'visitor can sign up with valid email address, password, name and org name' do number_orgs = Org.count number_users = User.count sign_up_with('test@example.com', 'please123', 'please123', 'simon', 'acme') txts = [I18n.t( 'devise.registrations.signed_up'), I18n.t( 'devise.registrations.signed_up_but_unconfirmed')] expect(page).to have_content(/.*#{txts[0]}.*|.*#{txts[1]}.*/) expect(User.count).to eq number_users + 1 expect(Org.count).to eq number_orgs + 1 expect(User.first.org). to eq Org.first end scenario 'visitor cannot sign up with existing org slug' do Org.delete_all org1 = Org.create name: 'Acme Ltd' expect(org1.id).to be_present sign_up_with('test@example.com', 'please123', 'please123', 'simon', 'Acme Ltd') expect(page).to have_content "Organization name has already been taken" end scenario 'visitor cannot sign up with missing name' do sign_up_with('test@example.com', 'please123', 'please123', '', 'acme') expect(page).to have_content "Name can't be blank" end scenario 'visitor cannot sign up with missing org name' do sign_up_with('test@example.com', 'please123', 'please123', 'simon', '') expect(page).to have_content "Organization name can't be blank" end # Scenario: Visitor cannot sign up with invalid email address # Given I am not signed in # When I sign up with an invalid email address # Then I see an invalid email message scenario 'visitor cannot sign up with invalid email address' do sign_up_with('bogus', 'please123', 'please123', 'simon', 'acme') expect(page).to have_content 'Email is invalid' end # Scenario: Visitor cannot sign up without password # Given I am not signed in # When I sign up without a password # Then I see a missing password message scenario 'visitor cannot sign up without password' do sign_up_with('test@example.com', '', '', 'simon', 'acme') expect(page).to have_content "Password can't be blank" end # Scenario: Visitor cannot sign up with a short password # Given I am not signed in # When I sign up with a short password # Then I see a 'too short password' message scenario 'visitor cannot sign up with a short password' do sign_up_with('test@example.com', 'please', 'please', 'simon', 'acme') expect(page).to have_content "Password is too short" end # Scenario: Visitor cannot sign up without password confirmation # Given I am not signed in # When I sign up without a password confirmation # Then I see a missing password confirmation message scenario 'visitor cannot sign up without password confirmation' do sign_up_with('test@example.com', 'please123', '', 'simon', 'acme') expect(page).to have_content "Password confirmation doesn't match" end # Scenario: Visitor cannot sign up with mismatched password and confirmation # Given I am not signed in # When I sign up with a mismatched password confirmation # Then I should see a mismatched password message scenario 'visitor cannot sign up with mismatched password and confirmation' do sign_up_with('test@example.com', 'please123', 'mismatch', 'simon', 'acme') expect(page).to have_content "Password confirmation doesn't match" end end
require 'formula' class Mecab < Formula homepage 'http://mecab.sourceforge.net/' url 'https://mecab.googlecode.com/files/mecab-0.996.tar.gz' sha1 '15baca0983a61c1a49cffd4a919463a0a39ef127' bottle do revision 1 sha1 "73f5e7206a4482f7ab714b0690ad3eeac7f0c9e0" => :yosemite sha1 "530ee77a2f13cce3225abd0cd9401858219959d9" => :mavericks sha1 "9747369cd4c0aa246e6a973c4f2e5652e174bae8" => :mountain_lion end def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make install" end end
cask "jd-gui-custom" do version "" sha256 "b16ce61bbcfd2f006046b66c8896c512a36c6b553afdca75896d7c5e27c7477d" # github.com/java-decompiler/jd-gui/ was verified as official when first introduced to the cask url "http://artifactory.generagames.com:8081/artifactory/generic-local/macos/utilities/jd-gui/jd-gui-.tar.dmg" appcast "https://github.com/java-decompiler/jd-gui/releases.atom" name "JD-GUI" desc "Standalone Java Decompiler GUI" homepage "http://jd.benow.ca/" app "jd-gui-osx-#{version}/JD-GUI.app" zap trash: "~/Library/Saved Application State/jd.jd-gui.savedState" end
class TwitterFeed def self.from source TwitterFeed.new(source: source) end attr_reader :source def initialize params @source = params.fetch(:source) end def tweets Tweet.from_twitter Twitter.user_timeline(source) end end class Tweet def self.from_twitter tweets Array(tweets).map{|t| new(t)} end attr_reader :original_tweet def initialize tweet @original_tweet = tweet end def source original_tweet.attrs[:user][:screen_name] end def body original_tweet.attrs[:text] end end
class Actor < ApplicationRecord # Direct associations has_many :filmographies, class_name: "Role" # Indirect associations # Validations # Scopes def to_s first_name end end
# RVM bootstrap # $:.unshift(File.expand_path("~/.rvm/lib")) set :application, "quiz" set :repository, "git@github.com:EnOD/quiz.git" set :rvm_ruby_string, 'ruby-1.9.2@quiz' set :rvm_type, :user require "rvm/capistrano" set :scm, :git set :branch, "master" set :git_shallow_clone, 1 set :deploy_via, :checkout set :deploy_to, "~/web/quiz" default_run_options[:pty] = true set :user, "enod" set :use_sudo, false server "guki.org", :app, :web, :db, :primary => true after "deploy:update", 'deploy:symlink' after "deploy:symlink", 'deploy:cleanup' # after "deploy:bundle", 'deploy:whenever' after "deploy", "deploy:bundle" # after "deploy:bundle", "apache:restart" namespace :deploy do task :symlink do run "ln -nfs #{shared_path}/log #{release_path}/log" run "ln -nfs #{shared_path}/config/database.yml #{release_path}/config/database.yml" end task :bundle do run "cd #{release_path} && bundle install" run "cd #{release_path} && bundle exec rake db:migrate RAILS_ENV=production" end end namespace :apache do [:stop, :start, :restart, :reload].each do |action| desc "#{action.to_s.capitalize} Apache" task action, :roles => :web do invoke_command "/etc/init.d/apache2 #{action.to_s}", :via => run_method end end end
# -*- encoding : utf-8 -*- class Scorecard < ActiveRecord::Base include UUID as_enum :tee_box_color, [:red, :white, :blue, :black, :gold], prefix: true, map: :string as_enum :direction, [:hook, :pure, :slice], prefix: true, map: :string belongs_to :player belongs_to :hole has_many :strokes scope :finished, -> { where.not(score: nil) } scope :sorted, -> { order(:number) } scope :out, -> { where(number: 1..9) } scope :in, -> { where(number: 10..18) } def double_eagle? par - score > 2 end def eagle? par - score == 2 end def birdie? par - score == 1 end def par? score == par end def bogey? score - par == 1 end def double_bogey? score - par > 1 end def finished? score end def status score - par if score and par end def distance_from_hole distance_from_hole_to_tee_box - driving_distance if driving_distance end def up_and_downs? (strokes.last.sequence == 1 and distance_from_hole_to_tee_box <= 100) or (strokes.last.sequence == 2 and strokes.last.club_pt? and distance_from_hole_to_tee_box <= 100) or (strokes.last.sequence == 2 and !strokes.last.club_pt? and strokes.last.distance_from_hole <= 100) or (strokes.last.sequence > 2 and strokes.last.club_pt? and !strokes.last(2).first.club_pt? and strokes.last(3)[0].distance_from_hole <= 100) or (strokes.last.sequence > 2 and !strokes.last.club_pt? and strokes.last(2).first.distance_from_hole <= 100) end def chip_ins? strokes.select{|stroke| stroke.club_pt?}.count.zero? end def update_simple options = {} options[:driving_distance] = (distance_from_hole_to_tee_box - options.delete(:distance_from_hole)).abs update!(options) calculate_player_and_statistic_and_leaderboard! end def update_professional options = {} ActiveRecord::Base.transaction do strokes.map(&:destroy!) new_strokes = options[:strokes].map do |stroke_params| raise InvalidDistance.new unless stroke_params[:distance_from_hole] raise InvalidPointOfFall.new unless Stroke.point_of_falls.keys.include?(stroke_params[:point_of_fall]) raise InvalidClub.new unless Stroke.clubs.keys.include?(stroke_params[:club]) Stroke.new(scorecard: self, distance_from_hole: stroke_params[:distance_from_hole].to_i, point_of_fall: stroke_params[:point_of_fall], penalties: stroke_params[:penalties], club: stroke_params[:club]) end raise HoledStrokeNotFound.new unless new_strokes.last.distance_from_hole.zero? raise DuplicatedHoledStroke.new if new_strokes.select{|stroke| stroke.distance_from_hole.zero?}.count > 1 new_strokes.map(&:save!) self.putts = strokes.reload.select{|stroke| stroke.club_pt?}.count self.penalties = (strokes.map{|stroke| stroke.penalties}.compact.reduce(:+) || 0) self.score = strokes.count + self.penalties self.driving_distance = (distance_from_hole_to_tee_box - strokes.first.distance_from_hole).abs if strokes.first self.direction = (if strokes.first.point_of_fall_left_rough? :hook elsif strokes.first.point_of_fall_right_rough? :slice else :pure end) if strokes.first save! end calculate_player_and_statistic_and_leaderboard! end def calculate_player_and_statistic_and_leaderboard! player.calculate! player.statistic.calculate! player.match.calculate_leaderboard! end end
class UsersController < ApplicationController before_filter :check_administrator_role, :only => [ :index, :destroy, :enable ] before_filter :login_required, :except => [ :new, :create ] # GET /users # GET /users.json def index @users = User.all respond_to do |format| format.html # index.html.erb format.json { render json: @users } end end # GET /users/1 # GET /users/1.json =begin def show @user = User.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @user } end end =end # GET /users/new # GET /users/new.json def new @user = User.new @categories = Category.all @layout = "one-col" @marquee = "marquee_sm.png" respond_to do |format| format.html # new.html.erb format.json { render json: @user } end end # GET /users/1/edit or /users/:userid/edit def edit if params[:id] @user = User.find(params[:id]) else @user = logged_in_user end end # POST /users # POST /users.json def create @user = User.new(params[:user]) respond_to do |format| if @user.save #AccountMailer.welcome_email(@user).deliver @user.profile ||= Profile.new @user.profile.gender = params[:gender] UserMailer.welcome_email(@user).deliver if params[:a] && !params[:a].empty? address = Address.new address.geocode params[:a] profile_address = ProfileAddress.new :profile => @user.profile, :address => address, :label => "Default Address", :default => @user.profile.profile_addresses.count.to_i.zero? address.destroy unless !address.geocode.nil? and address.save and profile_address.save end if params[:categories] params[:categories].each do | name, id | if @category = Category.find_by_id(id) @user.categories << @category if !(@user.has_category?(@category.id)) end end else Category.all.each do | category | @user.categories << category if !(@user.has_category?(category.id)) end end if logged_in_user format.html { redirect_to users_url, notice: "Congratulations! User Account has been created." } format.json { render json: @user, status: :created, :location => @user } else self.logged_in_user = User.authenticate(params[:user][:email], params[:user][:password]) format.html { redirect_to index_url, notice: "Congratulations! Your User Account has been created. Welcome to DealMyLife.com!" } end else format.html { render action: "new" } format.json { render json: @user.errors, status: :unprocessable_entity } end end end # PUT /users/1 # PUT /users/1.json def update @user = User.find(params[:id]) respond_to do |format| if @user.update_attributes(params[:user]) #format.html { post_to :controller => "account", action: "logout", notice: "User Account has been updated." } format.html { redirect_to profile_url, notice: "Password has been successfully updated." } format.json { head :ok } else format.html { render action: "edit" } format.json { render json: @user.errors, status: :unprocessable_entity } end end end # DELETE /users/1 # DELETE /users/1.json def destroy @user = User.find(params[:id]) @user.destroy respond_to do |format| format.html { redirect_to users_url } format.json { head :ok } end end # PUT /users/:id/enable # PUT /users/:id/enable.json def enable @user = User.find(params[:id]) respond_to do |format| if @user.update_attribute(:enabled, true) format.html { redirect_to users_url, notice: "User Enabled" } format.json { head :ok } else format.html { redirect_to users_url, notice: "There was an error enabling this User" } format.json { render json: @user.errors, status: :unprocessable_entity } end end end # PUT /users/:id/disable # PUT /users/:id/disable.json def disable @user = User.find(params[:id]) respond_to do |format| if @user.update_attribute(:enabled, false) format.html { redirect_to users_url, notice: "User Disabled" } format.json { head :ok } else format.html { redirect_to users_url, notice: "There was an error disabling this User" } format.json { render json: @user.errors, status: :unprocessable_entity } end end end end
class CreateEconsiders < ActiveRecord::Migration[5.2] def change create_table :econsiders do |t| t.string :title t.string :post_heading t.string :author t.text :post t.timestamps end end end
class VoicemailGreetingFormatValidator < ActiveModel::Validator ACCEPTABLE_MIME_TYPES = [ "audio/mpeg", "audio/wav", "audio/wave", "audio/x-wav", "audio/aiff", "audio/x-aifc", "audio/x-aiff", "audio/x-gsm", "audio/gsm", "audio/ulaw", ].freeze def validate(record) return unless voicemail_greeting_attached?(record) return if valid_voicemail_greeting_format?(record) record.errors[:voicemail_greeting] << "Invalid Voicemail Greeting Mimetype" end private def voicemail_greeting_attached?(record) record.voicemail_greeting.attached? end def valid_voicemail_greeting_format?(record) record.voicemail_greeting.content_type.in?(ACCEPTABLE_MIME_TYPES) end end
class Category < ActiveRecord::Base attr_accessible :name, :parent_id validates_presence_of :name acts_as_nested_set has_many :tickets def name_with_ancestors self_and_ancestors.collect(&:name).join(' >> ') end end
ActiveAdmin.register Publication do permit_params :title, :published_at, :description, :cover, :download index do selectable_column column :title column :published_on actions end show do div do raw publication.description end end sidebar "Cover", only: :show do image_tag publication.cover.try(:url, :large) end #filter :email #filter :current_sign_in_at #filter :sign_in_count #filter :created_at form do |f| f.inputs "Publication Details" do f.input :title f.input :published_on, label: "Publication date" f.input :description, as: :html_editor end f.inputs "Images" do div do image_tag(f.object.cover.try(:url, :small)) end f.input :cover #, as: :file end f.inputs "Downloads" do div do f.input :download #, as: file end end f.actions end end
FactoryGirl.define do factory :trial do sequence(:title) { |n| "Trial #{n}" } minimum_age_original "1 year" maximum_age_original "60 years" after(:build) do |trial| if trial.sites.empty? trial.sites << build(:site, trial: trial) end end trait :without_sites do after(:build) do |trial| trial.sites = [] end end end end
Factory.define :product do |p| p.sequence(:name) {|n| "Test Product #{n}"} p.url "http://www.example.com/test-product" p.price 12.00 p.size "Small,Medium,Large" end
class PodcastPresenter < BasePresenter presents :podcast delegate :name, to: :podcast def linked_name h.content_tag :h2, h.link_to(podcast.name, h.podcast_path(podcast)) end def description h.content_tag :p, podcast.description end def episodes_count Episode.where(podcast_id: podcast.id).count end def since_last_episode if episode = podcast.latest_episode content = h.distance_of_time_in_words(DateTime.now, episode.published_at) + " ago" else content = '&nbsp' end h.content_tag :td, h.raw(content), class: since_color_code(episode) end def since_color_code(episode) if episode distance = Date.today - episode.published_at.to_date if distance <= 14 "ok" elsif distance > 14 && distance <= 28 "alert" else "warning" end end end def until_next_episode if episode = podcast.episodes.scheduled.first episode.published_at.strftime("%d.%m.%y %H:%M") else '&nbsp' end end def top_episode episode = podcast.episodes.order('downloads DESC').first h.content_tag :a, "##{episode.num} #{episode.title}", href: "#", data: { tooltip: "" }, title: "#{episode.downloads} Downloads", class: 'has-tip tip-top' end def artwork_thumb(size) if podcast.artwork? h.content_tag :div, class: "th radius" do h.link_to h.image_tag(podcast.artwork.url(size)), podcast end end end def artwork(size) h.image_tag podcast.artwork.url(size) if podcast.artwork? end def subscribers Subscriber.latest(podcast).sum('count') end def subscribers_chart_data Subscriber.latest(podcast).as_json end def bookmarklet_link "javascript:function toi1(){var d=document,z=d.createElement('scr'+'ipt'),b=d.body,l=d.location,t=d.title;try{if(!b) throw(0);z.setAttribute('src','#{h.root_url}show_notes/#{podcast.name}.js?u='+encodeURIComponent(l.href)+'&t='+encodeURIComponent(t));b.appendChild(z);}catch(e){alert('Please wait until the page has loaded.');}}toi1();void(0)" end ## Feed def uri h.podcast_url(podcast) end def pubDate episodes_count > 0 ? podcast.episodes.maximum('published_at').to_s(:rfc822) : podcast.created_at.to_s(:rfc822) end def explicit podcast.explicit? ? 'yes' : 'clean' end def feed_artwork h.root_url + podcast.artwork.url(:original, false)[1..-1] end end
require 'rails_helper' RSpec.describe Movement, type: :model do def expect_required_field(field_name) movement = new_movement(field_name => nil) expect do movement.save(validate: false) end.to raise_error(ActiveRecord::NotNullViolation) expect(movement.save).to eql(false) end it "saves a movement to the database" do expect do new_movement.save end.to change { Movement.count }.by(1) end it "has a unique constraint on number/date" do date = Time.zone.now new_movement(date: date).save expect do new_movement(date: date).save(validate: false) end.to raise_error(ActiveRecord::RecordNotUnique) expect(new_movement(date: date).save).to eql(false) end it "has required fields" do expect_required_field(:number) expect_required_field(:date) expect_required_field(:amount) expect_required_field(:movement_type) expect_required_field(:raw) end it "validates the movement_type" do expect do new_movement(movement_type: "a-type-that-does-not-exist").save! end.to raise_error(ActiveRecord::RecordInvalid) end describe ".from_row" do let(:csv_row) { csv_rows("recordbank_vpn").first } let(:movement_row) { MovementRow.new(csv_row) } it "creates a movement from a CSV row" do expect do movement = Movement.from_row(movement_row) end.to change { Movement.count }.by(1) end it "maps all the fields correctly" do movement = Movement.from_row(movement_row) expect(movement.number).to eql(movement_row.number) expect(movement.date).to eql(DateTime.parse(movement_row.date).utc) expect(movement.amount).to eql(movement_row.amount) expect(movement.iban).to eql(movement_row.iban) expect(movement.communication).to eql(movement_row.communication) expect(movement.movement_type).to eql(movement_row.movement_type) expect(movement.raw).to eql(movement_row.row.to_s) end end end
class DeviseCreateUsers < ActiveRecord::Migration def self.up # Remove columns used by old Restful Authentication plugin remove_column :users, :crypted_password remove_column :users, :salt # Add columns used by Devise add_column :users, :encrypted_password, :string, :limit => 128, :null => false, :default => "" add_column :users, :password_salt, :string, :null => false, :default => "" add_column :users, :reset_password_token, :string add_column :users, :remember_created_at, :datetime add_column :users, :sign_in_count, :integer, :default => 0 add_column :users, :current_sign_in_at, :datetime add_column :users, :last_sign_in_at, :datetime add_column :users, :current_sign_in_ip, :string add_column :users, :last_sign_in_ip, :string add_index :users, :email, :unique => true add_index :users, :reset_password_token, :unique => true end def self.down # Drop columns used by Devise drop_column :users, :last_sign_in_ip drop_column :users, :current_sign_in_ip drop_column :users, :last_sign_in_at drop_column :users, :current_sign_in_at drop_column :users, :sign_in_count drop_column :users, :remember_created_at drop_column :users, :reset_password_token drop_column :users, :password_salt drop_column :users, :encrypted_password # Add columns used by Restful Authentication add_column :users, :salt, :string add_column :users, :crypted_password, :string end end
class CreatePlaceReviews < ActiveRecord::Migration def self.up create_table :place_reviews do |t| t.references :place t.references :by t.references :sortie t.integer :score t.text :comment t.timestamps end end def self.down drop_table :place_reviews end end
class Router def initialize @controller = Controller.new end def perform system 'clear' puts "Bienvenue dans The Gossip Project".red while true puts "Que veux tu faire l'ami?".yellow.bold puts "1. Je veux creer un gossip".green puts "2. Afficher les POTINS".green puts "3. Je veux delete un gossip!".green puts "4. Je veux quitter l'app".green params = gets.chomp.to_i#variable input case params #case en fonction du choix when 1 puts "Tu as choisi de creer un gossip" @controller.create_gossip when 2 puts "Tu veux voir ce qu'il se dit dans la zone!!!" @controller.gossip_index when 3 puts "On va delete รงa vite fait bien fait !" @controller.delete_potin when 4 puts "HASTA LA VISTA BABY!!!".blue break else puts "Ce choix n'existe pas, merci de rรฉessayer." end end end end
class CreateAdvertisement < ROM::Commands::Create[:sql] register_as :create relation :advertisements result :one end
class ScoreCardScorer < ActiveRecord::Base attr_accessible :score_card_id, :scorer_id belongs_to :score_card validates :score_card_id, presence: true validates :scorer_id, presence: true end
json.array!(@admin_api_settings) do |admin_api_setting| json.extract! admin_api_setting, :id json.url admin_api_setting_url(admin_api_setting, format: :json) end
module Ovpnmcgen VERSION = "0.4.2" SUMMARY = "An OpenVPN iOS Configuration Profile (.mobileconfig) Utility" end
require 'cutest' require 'mock_server' require_relative '../lib/net/http/pool' extend MockServer::Methods mock_server { get '/' do 'What is up dog!' end get '/marco' do 'polo' end post '/post' do params[:test] ? 'this is a test' : 'the post' end put '/put' do params[:run] || 'the put' end get '/wait' do sleep 5 "Finally!" end delete('/delete') {} } scope do setup do @pool = Net::HTTP::Pool.new("http://localhost:4000/") end test "check that the HTTP verbs do work" do request = Net::HTTP::Get.new("/") @pool.request(request) do |res| assert_equal "200", res.code assert_equal 'What is up dog!', res.body end request = Net::HTTP::Get.new("/marco") @pool.request(request) do |res| assert_equal "200", res.code assert_equal 'polo', res.body end request = Net::HTTP::Post.new("/post") request.body = 'test=test' request['X-Fancy-Header'] = 'Sometimes' @pool.request(request) do |res| assert_equal "200", res.code assert_equal 'this is a test', res.body end request = Net::HTTP::Put.new("/put") request.body = 'run=fast' @pool.request(request) do |res| assert_equal "200", res.code assert_equal 'fast', res.body end request = Net::HTTP::Delete.new("/delete") @pool.request(request) do |res| assert_equal "200", res.code end end test "do not block main thread when resource is slow" do start = Time.now request = Net::HTTP::Get.new("/wait") 5.times { @pool.request(request) {} } assert Time.now - start < 20 end end
module Zaypay # Errors that can be raised by the Zaypay gem class Error < StandardError def initialize(type = nil, message = "Error thrown by the Zaypay gem.") @type = type super(message) end attr_accessor :type end end
class Beacon include Mongoid::Document include Mongoid::Timestamps include Mongoid::Spacial::Document include Mongoid::Realization belongs_to :user field :geo, type: Array, spacial: true field :text, type: String def as_json(options={}) { id: id, updated_at: updated_at.to_i, geo: geo, text: text, user: user.as_json } end end
Given /^the website has been populated with content based on the site map$/ do seed_file = File.join(Rails.root, "demo", "seeds.rb") load(seed_file) end When /^I click on a root$/ do @_page = Noodall::Node.roots.last within("tbody tr:last") { click_link "Children" } end Then /^I should see a list the of the root's children$/ do @_page.children.each do |child| page.should have_content(child.title) end end When /^I click on a child$/ do @_child = @_page.children.first within(:css, "tbody tr:first") { click_link "Children" } end Then /^I should see a list of the child's children$/ do @_child.children.each do |gchild| page.should have_content(gchild.title) end end Then /^I should be able to create a new root$/ do click_link 'New' fill_in 'Title', :with => 'New Root' click_button 'Create' page.should have_content(' was successfully created.') end Then /^I should see the root listed within the roots$/ do visit noodall_admin_nodes_path page.should have_content('New Root') end Then /^I should be able to create a new child$/ do click_link 'New' fill_in 'Title', :with => 'New Child' click_button 'Create' page.should have_content(' was successfully created.') end Then /^I should see the child listed within the root's children$/ do visit noodall_admin_node_nodes_path(@_page) page.should have_content('New Child') end Then /^I should be able to delete content$/ do @_deleted_node = Noodall::Node.roots.last @_deleted_node_children = @_deleted_node.children within(:css, 'table tbody tr:last') { click_link "Delete" } page.should have_content("deleted") end Then /^the content and all of it's sub content will be removed from the website$/ do lambda { visit node_path(@_deleted_node) }.should raise_error(MongoMapper::DocumentNotFound) @_deleted_node_children.each do |child| lambda { visit node_path(child) }.should raise_error(MongoMapper::DocumentNotFound) end end Then /^I should be able to move a child content to another parent$/ do @_child = @_page.children.first @_new_parent = Noodall::Node.roots.first within(:css, "table tbody tr#node-#{@_child.id}") { click_link "Edit" } # Simulates what we are now doing with JS click_link "Advanced" within(:css, '#parent-title' ) { click_link "Edit" } within(:css, 'ol.tree' ) { click_link @_new_parent.title } click_button 'Draft' end Then /^I should see the child listed within the other parent's children$/ do visit noodall_admin_node_nodes_path(@_new_parent) within('tbody') do page.should have_content(@_child.title) end end Then /^I should be able change the order of the root's children$/ do table = table(tableish("table tr", 'td, th')) title = table.hashes[2]['Title'] # 2 as zero index within(:css, 'table tbody tr:nth(3)') { click_link "up" } table = table(tableish("table tr", 'td, th')) table.hashes[1]['Title'].should == title within(:css, 'table tbody tr:nth(2)' ) { click_link "down" } within(:css, 'table tbody tr:nth(3)' ) { click_link "down" } table = table(tableish("table tr", 'td, th')) table.hashes[3]['Title'].should == title end When /^I create a new child under an ancestor in "([^"]+)" template$/ do |template_title| template = template_title.downcase.gsub(' ','_') #create the ancester parent = Factory(template.to_sym) visit noodall_admin_node_nodes_path(parent) click_link 'New' end Then /^I should be able select a template from the "([^"]+)"$/ do |sub_template_string| sub_templates = sub_template_string.split(', ') sub_templates.each do |sub_template| choose sub_template end end Then /^I should see a list of the roots$/ do Noodall::Node.roots.each do |root| page.should have_content(root.title) end end
class FactoriesController < ApplicationController layout "application_control" before_filter :authenticate_user! #load_and_authorize_resource def bigscreen @factory = current_user.factories.find(iddecode(params[:id])) @other_quotas = [Setting.quota.inflow, Setting.quota.outflow, Setting.quota.outmud, Setting.quota.power] gon.lnt = @factory.lnt gon.lat = @factory.lat gon.title = @factory.name end def index @factory = Factory.new @factories = Factory.all end def show @factory = Factory.where(:id => params[:id]).first end def new @factory = Factory.new @factory.departments.build end def create @factory = Factory.new(factory_params) #@factory.user = current_user if @factory.save redirect_to :action => :index else render :new end end def edit @factory = current_user.factories.find(iddecode(params[:id])) end def update @factory = current_user.factories.find(iddecode(params[:id])) if @factory.update(factory_params) redirect_to edit_factory_path(idencode(@factory.id)) else render :edit end end def destroy @factory = Factory.where(:id => params[:id]).first @factory.destroy redirect_to :action => :index end private def factory_params params.require(:factory).permit( :area, :name, :info, :lnt, :lat , :logo, departments_attributes: department_params, mudfcts_attributes: mudfct_params) end def department_params [:id, :name, :info ,:_destroy] end def mudfct_params [:id, :name, :ability ,:_destroy] end end
class Admin::ServiceGroupsController < ApplicationController def new @company = Company.find(params[:company_id]) @service_group = ServiceGroup.new end def create @company = Company.find(params[:company_id]) @service_group = @company.service_groups.create(service_group_params) redirect_to admin_company_path(@company) end private def service_group_params params.require(:service_group).permit(:title) end end
require 'rails_helper' require 'helpers/requests' require 'shared/requests' RSpec.describe 'Measurements', :type => :request do describe 'GET /api/v1/channels/:code/measurements' do let(:channel) { create(:channel_with_measurements) } let(:pagination) { Hash.new } before { get api_v1_channel_measurements_path(channel.code, pagination) } it_behaves_like 'a successful response' it_behaves_like 'a listable resource' it_behaves_like 'a paginable resource' it { expect(body.count).to eq(24) } it { expect(body).to all include('value') } it { expect(body).to all include('time') } it { expect(body).to eq body.sort_desc_by('time') } end end
# Add sort_index column to the projects table class AddSortIndexToProjects < ActiveRecord::Migration[5.1] def change add_column :projects, :sort_index, :integer end end
class Kid < ActiveRecord::Base has_many :relationships has_many :users, through: :relationships has_many :reminders accepts_nested_attributes_for :relationships end
module Admin class SessionsController < AdminController skip_before_action :authenticate_user!, :must_be_admin!, only: [:create] def destroy # LOGOUT - requires authenticated user current_user.sign_out! render json: {success: true, message: 'Signed out successfully.'} end def create return missing_parameters unless (params[:email].present? && params[:password].present?) user = RegularUser.find_by(email: params[:email]) if user && user.authenticate(params[:password]) && user.admin? logger.warn "[SECURITY] User logged into admin controller: #{params[:email]}" user.sign_in! render json: user.session_data, status: 201 else return invalid_parameters("Email/password combination is invalid.") end end end end
# This lecture covers going further into inheritance # Some languages such as Java allow for multiple inheritance but Ruby only allows for single inheritance # Ruby gets around multiple inheritnace by allowing for Mixins class Animal attr_accessor :color, :name def initialize( color, name ) @color = color @name = name end # Self.class allows Ruby to ID what kind of class it is def identify return "I am a #{self.class}" end def speak return "hello my name is #{@name}" end end class Tiger < Animal # We can use super to add on/inhereit from the class above def speak return super + " grrrr" end end class Zebra < Animal # Here we use super to add additional features to the Zebra class # We have color, name returned to the parent class via super, but we also have stripes def initialize( color, name, stripes ) @stripes = stripes super(color, name) end end class Hyena < Animal end tiger = Tiger.new( "orange", "tigger" ) # The following speak method will override the speak method in the puts tiger.speak puts tiger.identify # The above returns Tiger, but not Animal, even though the ID method is in the animal class. This is because self is a Tiger object which then looks to the Animal class. zebra = Zebra.new( "black and white", "Zany", 20) puts zebra.inspect hyena = Hyena.new( "grey", "Hector") puts hyena.identify
class HeadlinerBox < ActiveRecord::Base belongs_to :article belongs_to :picture has_many :headliner_sections has_many :sections, :through => :headliner_sections has_many :headliner_articles has_many :articles, :through => :headliner_articles has_many :headliner_themes has_many :themes, :through => :headliner_themes has_many :flashphoto_headliners has_many :headliner_dailyquestions has_many :dailyquestions, :through => :headliner_dailyquestions def info inf = "" arr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZฤ›ลกฤล™ลพรฝรกรญรฉรบลฏรณฤลฅลˆรถรครซฤšล ฤŒล˜ลฝรรรร‰รšลฎร“ฤŽลคล‡ร–ร„ร‹ฤพฤฝรผรœรŸรŸ1234567890".split("") #arr = [".","!","?",":",";","\"","'","โ€œ","โ€","โ€š","โ€›","โ€ž","โ€ฒ","ห"] if !picture_title.blank? if !arr.include?(picture_title.last) inf += "#{picture_title}" else inf += "#{picture_title}." end end if picture inf += " #{picture.type_image.capitalize}" unless picture.type_image.blank? inf += " #{picture.author}" unless picture.author.blank? end return inf end end
class UsersController < ApplicationController # define a method def index @users = User.all # rails inplicte execute something like that render :html # For use angular, we must return the var @users in json render json: @users end def show @user = User.find(params[:id]) render json: @user end end
class Forgottoadd2 < ActiveRecord::Migration def change rename_column :notes, :from_id, :user_id end end
ActiveAdmin.register BannerInicio do belongs_to :seccion config.filters = false index do column :id column "Imagen", :img_url column "Enlace", :img_link column "Titulo", :img_titulo column :orden column :visible default_actions end form do |f| f.inputs "Formulario Banner Inicio" do f.input :img_url, :label => "Imagen" f.input :img_link, :label => "Enlace" f.input :img_titulo, :label => "Titulo" f.input :orden f.input :visible end f.actions end show do |ad| attributes_table do row :img_url do image_tag(ad.img_url.url) end row :img_link row :img_titulo row :orden row :visible end end end
class Category < ActiveRecord::Base has_many :categorizations, dependent: :destroy has_many :questions, through: :categorizations validates :name, presence: :true, uniqueness: :true end
require_dependency "keppler_frontend/application_controller" module KepplerFrontend module Admin # ViewsController class ViewsController < ::Admin::AdminController layout 'keppler_frontend/admin/layouts/application' before_action :set_view, only: [:show, :edit, :update, :destroy] before_action :show_history, only: [:index] before_action :set_attachments before_action :authorization before_action :only_development before_action :reload_views, only: [:index] after_action :update_view_yml, only: [:create, :update, :destroy, :destroy_multiple, :clone] before_action :reload_view_callbacks, only: [:index] after_action :update_view_callback_yml, only: [:create, :update, :destroy, :destroy_multiple, :clone] skip_before_action :verify_authenticity_token, only: :live_editor_save include KepplerFrontend::Concerns::Services # GET /views def index @q = View.ransack(params[:q]) views = @q.result(distinct: true) @objects = views.page(@current_page).where.not(name: 'keppler').order(position: :asc) @total = views.size @views = @objects.all if !@objects.first_page? && @objects.size.zero? redirect_to views_path(page: @current_page.to_i.pred, search: @query) end respond_to do |format| format.html format.xls { send_data(@views.to_xls) } format.json { render :json => @objects } end end # GET /views/1 def show end # GET /views/new def new @view = View.new end # GET /views/1/edit def edit end # POST /views def create @view = View.new(view_params) if @view.save && @view.install redirect_to admin_frontend_view_editor_path(@view), notice: actions_messages(@view) else render :new end end # PATCH/PUT /views/1 def update @view.delete_route @view.update_files(view_params) if @view.update(view_params) view = view_params.to_h @view.new_callback(@view, view[:view_callbacks_attributes]) redirect_to edit_admin_frontend_view_path(@view), notice: actions_messages(@view) else render :edit end @view.add_route end def clone @view = View.clone_record params[:view_id] if @view.save redirect_to admin_frontend_views_path else render :new end end # DELETE /views/1 def destroy if @view @view.uninstall @view.destroy end redirect_to admin_frontend_views_path, notice: actions_messages(@view) end def destroy_callback @view = View.find(params[:view_id]) @callback = ViewCallback.find(params[:view_callback_id]) @callback.destroy end def destroy_multiple View.destroy redefine_ids(params[:multiple_ids]) redirect_to( admin_frontend_views_path(page: @current_page, search: @query), notice: actions_messages(View.new) ) end def upload View.upload(params[:file]) redirect_to( admin_frontend_views_path(page: @current_page, search: @query), notice: actions_messages(View.new) ) end def sort View.sorter(params[:row]) @q = View.ransack(params[:q]) views = @q.result(distinct: true) @objects = views.page(@current_page) render :index end def editor @view = View.find(params[:view_id]) @files_list = resources.list @files_views = resources.custom_list('views') @partials = Partial.all @views = View.where.not(name: 'keppler').order(position: :asc) @functions = KepplerFrontend::Function.all end def editor_save @view = View.find(params[:view_id]) @view.code_save(params[:html], 'html') if params[:html] @view.code_save(params[:scss], 'scss') if params[:scss] @view.code_save(params[:js], 'js') if params[:js] @view.code_save(params[:js_erb], 'js_erb') if params[:js_erb] @view.code_save(params[:ruby], 'action') if params[:ruby] render json: {result: true} end def select_theme_view @view = View.where(id: params[:view_id]).first theme_view=File.readlines("#{url_front}/app/assets/html/keppler_frontend/views/#{params[:theme_view]}.html") theme_view = theme_view.join out_file = File.open("#{url_front}/app/views/keppler_frontend/app/frontend/#{@view.name}.html.erb", "w") out_file.puts("<keppler-view id='#{@view.name}'>\n #{theme_view}\n</keppler-view>"); out_file.close redirect_to admin_frontend_view_editor_path(params[:view_id]) end def live_editor_save view = View.where(id: params[:view_id]).first result = view.live_editor_save(params[:html], params[:css]) render json: { result: result} end private def authorization authorize View end def url_front "#{Rails.root}/rockets/keppler_frontend" end def reload_views yml = KepplerFrontend::Utils::YmlHandler yml = yml.new('views') yml.reload end def update_view_yml views = View.all yml = KepplerFrontend::Utils::YmlHandler yml = yml.new('views', views) yml.update end def reload_view_callbacks file = File.join("#{Rails.root}/rockets/keppler_frontend/config/view_callbacks.yml") view_callbacks = YAML.load_file(file) view_callbacks.each do |route| callback = KepplerFrontend::ViewCallback.where(name: route['name']).first unless callback KepplerFrontend::ViewCallback.create( name: route['name'], function_type: route['function_type'] ) end end end def update_view_callback_yml view_callbacks = ViewCallback.all file = File.join("#{Rails.root}/rockets/keppler_frontend/config/view_callbacks.yml") data = view_callbacks.as_json.to_yaml File.write(file, data) end def set_attachments @attachments = ['logo', 'brand', 'photo', 'avatar', 'cover', 'image', 'picture', 'banner', 'attachment', 'pic', 'file'] end # Use callbacks to share common setup or constraints between actions. def set_view @view = View.where(id: params[:id]).first end # Only allow a trusted parameter "white list" through. def view_params params.require(:view).permit(:name, :url, :root_path, :method, :active, :format_result, :position, :deleted_at, view_callbacks_attributes: view_callbacks_attributes) end def view_callbacks_attributes [:name, :function_type, :_destroy] end def redefine_ids(ids) ids.delete('[]').split(',').select do |id| View.find(id).uninstall if model.exists? id id if model.exists? id end end def show_history get_history(View) end def get_history(model) @activities = PublicActivity::Activity.where( trackable_type: model.to_s ).order('created_at desc').limit(50) end # Get submit key to redirect, only [:create, :update] def redirect(object, commit) if commit.key?('_save') redirect_to([:admin, :frontend, object], notice: actions_messages(object)) elsif commit.key?('_add_other') redirect_to( send("new_admin_frontend_#{underscore(object)}_path"), notice: actions_messages(object) ) end end end end end
require 'rails_helper' describe 'Merchant Discount New' do before :each do @merchant1 = Merchant.create!(name: 'Merchant 1') @merchant2 = Merchant.create!(name: 'Merchant 2') end it 'should be able to fill in a form and create a new discount' do visit new_merchant_discount_path(@merchant1) fill_in 'Discount Name', with: 'Dingley Doo Birthday' fill_in 'Percentage Discount', with: 75 fill_in 'Quantity Threshold', with: 10 click_button "Create Discount" expect(current_path).to eq(merchant_discounts_path(@merchant1)) expect(page).to have_content('Dingley Doo Birthday') expect(page).to have_content('Discount has been created!') end it "displays a message to the user if the new discount was not saved" do visit new_merchant_discount_path(@merchant2) fill_in 'Discount Name', with: '' fill_in 'Percentage Discount', with: '' fill_in 'Quantity Threshold', with: '' click_button 'Create Discount' expect(current_path).to eq(new_merchant_discount_path(@merchant2)) expect(page).to have_content('Discount was not saved. Try again.') end end
class NewsMailer < ActionMailer::Base default from: 'info@newsleter.localhost', template_path: 'mailers/news' def send_newsletter(news, acc) @news = news @acc = acc mail to: acc.email, subject: 'Newsletter' end end
# frozen_string_literal: true class PlacePresenter include Hydra::Presenter include RelatedAssetTerms def self.model_terms [ :location_type, :lat, :long ] end self.model_class = Place self.terms = model_terms + CitiResourceTerms.all def summary_terms [:uid, :name_official, :created_by, :resource_created, :resource_updated] end end
class MemoriesController < ApplicationController def index @memories = Memory.all end def show @memory = Memory.find(params[:id]) end def new @memory = Memory.new end def create memory = Memory.new(memory_params) memory.save redirect_to memory_path(memory.id) end def edit @memory = Memory.find(params[:id]) end def update memory = Memory.find(params[:id]) memory.update(memory_params) redirect_to memory_path(memory.id) end private def memory_params params.require(:memory).permit(:title, :body, :image) end end
class MessagesController < ApplicationController # GET /messages # GET /messages.json before_filter :signed_in_user, only: [:create] def index @messages = Message.all respond_to do |format| format.html # index.html.erb format.json { render json: @messages } end end # GET /messages/1 # GET /messages/1.json def show @message = Message.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @message } end end # GET /messages/new # GET /messages/new.json def new @message = Message.new respond_to do |format| format.html # new.html.erb format.json { render json: @message } end end # GET /messages/1/edit def edit @message = Message.find(params[:id]) end def create @message = current_user.messages.build(params[:message]) #micropost_params) if @message.save # flash[:success] = "Message created!" redirect_to root_url else render 'static_pages/home' end end # PUT /messages/1 # PUT /messages/1.json def update @message = Message.find(params[:id]) @message.inc(:likes, 1) redirect_to root_path end # DELETE /messages/1 # DELETE /messages/1.json def destroy @message = Message.find(params[:id]) @message.destroy respond_to do |format| format.html { redirect_to messages_url } format.json { head :no_content } end end end
require 'spec_helper' describe 'uru::install' do context 'unix' do let(:chef_run) do ChefSpec::Runner.new(platform: 'ubuntu', version: '12.04') do |node| end.converge(described_recipe) end context 'success' do before do stub_command("cat .bash_profile | grep 'eval \"$(uru_rt admin install)\"'").and_return(false) end it 'runs the install_uru bash script' do expect(chef_run).to run_bash('install_uru') end end context 'failure' do before do stub_command("cat .bash_profile | grep 'eval \"$(uru_rt admin install)\"'").and_return(true) end it "doesn't run the install_uru bash script" do expect(chef_run).to_not run_bash('install_uru') end end end end
class RenameRedactorAssets < ActiveRecord::Migration def self.up rename_table :redactor_assets, :redactor2_assets end def self.down rename_table :redactor2_assets, :redactor_assets end end
namespace :memcached do desc 'Flush memcached server' task :flush, roles: :app do run "echo 'flush_all' | nc localhost 11211" end end
module Api module V1 class RequestInformationsController < Api::V1::ApplicationController def amount_of_status amount_status = RequestInformation.amount_of_status(params[:status]) render json: { amount_of_status: amount_status }, status: :ok end def amount_of_paths amount_paths = RequestInformation.amount_of_paths(params[:path]) render json: { amount_of_paths: amount_paths }, status: :ok end def amount_of_ips amount_ips = RequestInformation.amount_of_ips(params[:client_ip]) render json: { amount_of_ips: amount_ips }, status: :ok end def amount_of_many_requests amount_many_requests = RequestInformation.amount_of_many_requests render json: { amount_of_many_requests: amount_many_requests }, status: :ok end private def request_information_params params .require(:request_information) .permit(:client_ip, :status, :path) end end end end
# frozen_string_literal: true require_relative 'mixins/command' # attach-session (alias: attach) # [-dErx] [-c working-directory] [-f flags] [-t target-session] module Build module Util class Tmux module AttachSession include Mixins::Command aka :attach switch d: :detach_clients switch E: :skip_environment_update switch r: :read_only switch x: :sighup flag c: :working_directory flag f: :flags flag t: :target_session end end end end
module GrapeApi class API < Grape::API version 'v1', using: :path format :json prefix :api helpers do # def check_token # if params[:auth_token] # @current_user = User.find_by_token(params[:auth_token]) # else # @current_user = nil # end # end # def require_login # error!("Requied login", 401) unless current_user # end # def current_user # @current_user # end def v1_products_url(x) "/api/v1/products?page=#{x.values[0]}" end def v1_products_url(page) "/api/v1/grape/products?page=#{page.values[0]}" end def store_product_url(product) "/store/products/#{product.id}" end end resource :grape do get :products do # require_login @products = Product.page( params[:page] ).per(1) { data: [ url: store_product_url(@products[0]), name: @products[0].name, description: @products[0].description, qty: @products[0].qty, price: @products[0].price, created_at: @products[0].created_at, updated_at: @products[0].updated_at ], paging:{ current_page: @products.current_page, total_pages: @products.total_pages, per_page: @products.limit_value, next_url: (@products.last_page?)? nil : v1_products_url( page: @products.next_page ), previous_url: (@products.first_page?)? nil : v1_products_url( page: @products.prev_page ) } } end end end end
require 'rails_helper' RSpec.feature "following friends" do before do @john=User.create(first_name:"John",last_name:"Doe",email:"john@example.com",password:"password") @peter=User.create(first_name:"Peter",last_name:"Smith",email:"peter@example.com",password:"password") login_as @john end scenario "with signed in users" do visit '/' expect(page).to have_content(@john.full_name) expect(page).to have_content(@peter.full_name) expect(page).not_to have_link("Follow",:href =>"/friendships?friend_id=#{@john.id}") link="a[href='/friendships?friend_id=#{@peter.id}']" find(link).click expect(page).not_to have_link("Follow",:href=>"/friendships?friend_id=#{@peter.id}") end end
class Hash def keys_of(*arguments) # Take arguments, these are values. array_of_keys = [] # Checks the given hash for the values. each do |key, value| if arguments.include?(value) # Stores the keys of the matching values. array_of_keys << key end end # Returns array of keys. array_of_keys end end
# == Schema Information # # Table name: bwc_codes_constant_values # # id :integer not null, primary key # completed_date :date # employer_type :integer default(0) # name :string # rate :float # start_date :date # created_at :datetime # updated_at :datetime # class BwcCodesConstantValue < ActiveRecord::Base require 'activerecord-import' require 'open-uri' scope :current_rate, -> { private_employer.find_by(name: :administrative_rate, completed_date: nil) } scope :current_public_rate, -> { public_employer.find_by(name: :administrative_rate, completed_date: nil) } enum employer_type: [:private_employer, :public_employer] def self.import_table(url) time1 = Time.new puts "Start Time: " + time1.inspect # Democ.transaction do conn = ActiveRecord::Base.connection rc = conn.raw_connection rc.exec("COPY bwc_codes_constant_values (name, rate, start_date) FROM STDIN WITH CSV") file = open(url) while !file.eof? # Add row to copy data rc.put_copy_data(file.readline) end # We are done adding copy data rc.put_copy_end # Display any error messages while res = rc.get_result if e_message = res.error_message p e_message end end time2 = Time.new puts "End Time: " + time2.inspect end end
require 'spec_helper' describe 'DataMagic::Config #field_types' do let(:config) { DataMagic::Config.new(load_datayaml: false) } it "returns empty if dictionary is empty" do allow(config).to receive(:file_config).and_return([{'name' => 'one.csv'}]) allow(config).to receive(:dictionary).and_return({}) expect(config.field_types).to eq({}) end context "when no type is given" do before do allow(config).to receive(:file_config).and_return([{'name' => 'one.csv'}]) allow(config).to receive(:dictionary).and_return({ 'name' => {source:'NAME_COLUMN'} }) end it "defaults to string" do expect(config.field_types).to eq({ 'name' => 'string' }) end end it "supports integers" do allow(config).to receive(:file_config).and_return([{'name' => 'one.csv'}]) allow(config).to receive(:dictionary).and_return( IndifferentHash.new count: {source:'COUNT_COLUMN', type: 'integer'} ) expect(config.field_types).to eq({'count' => 'integer'}) end context "with float type" do it "sets float mapping" do allow(config).to receive(:file_config).and_return([{'name' => 'one.csv'}]) allow(config).to receive(:dictionary).and_return( IndifferentHash.new percent: {source:'PERCENT_COLUMN', type: 'float'} ) expect(config.field_types).to eq({'percent' => 'float'}) end it "can be excluded" do allow(config).to receive(:dictionary).and_return( IndifferentHash.new id: {source:'ID', type: 'integer'}, percent: {source:'PERCENT', type: 'float'} ) allow(config).to receive(:file_config).and_return([ IndifferentHash.new({ name:'one.csv', only: ['id'] }) ]) expect(config.field_types).to eq({'id' => 'integer'}) end it "can be nested" do allow(config).to receive(:dictionary).and_return( IndifferentHash.new id: {source:'ID', type: 'integer'}, percent: {source:'PERCENT', type: 'float'} ) allow(config).to receive(:file_config).and_return([ IndifferentHash.new({name:'one.csv', only: ['id']}), IndifferentHash.new({name:'two.csv', nest: {key: '2012', contents: ['percent']}}) ]) expect(config.field_types).to eq({ 'id' => 'integer', '2012.percent' => 'float' }) end end it "supports special case for location fields as nil" do # special case for location in create_index allow(config).to receive(:dictionary).and_return( IndifferentHash.new 'location.lat': {source:'LAT_COLUMN'}, 'location.lon': {source:'LON_COLUMN'} ) expect(config.field_types).to eq({}) end end
# == Schema Information # # Table name: release_order_application_with_versions # # id :integer not null, primary key # release_order_id :integer # application_with_version_id :integer # describe ReleaseOrderApplicationWithVersion, type: :model do it { is_expected.to have_many(:release_order_application_with_version_envs) } it { is_expected.to have_many(:envs).through(:release_order_application_with_version_envs) } end
require_relative 'spec_helper' require 'Rspec' require_relative '../lib/customer' describe Customer do before :each do @c = Customer.new({ :id => '1', :first_name => 'Joan', :last_name => 'Clarke', :created_at => '2016-01-11 09:34:06 UTC', :updated_at => '2007-06-04 21:35:10 UTC', }) end it '#customer' do expect(@c).to be_a Customer end it '#id' do expect(@c.id).to eq 1 end it '#first_name' do expect(@c.first_name).to eq 'Joan' end it '#last_name' do expect(@c.last_name).to eq 'Clarke' end it '#created_at' do expect(@c.created_at).to be_a Time end it '#updated_at' do expect(@c.updated_at).to be_a Time end end
class FulfillmentMailer < ApplicationMailer default from: "[CTRL]ALT <orders@#{ENV['app_url']}>" def in_transit(fulfillment) @fulfillment = fulfillment @order = @fulfillment.order @shipping_address = @fulfillment.shipping_address @line_items = @fulfillment.line_items mail(to: @order.email, subject: "##{@order.guid} is on the way!") end def shipment_delivered(fulfillment) @fulfillment = fulfillment @order = @fulfillment.order @shipping_address = @fulfillment.shipping_address @line_items = @fulfillment.line_items mail(to: @order.email, subject: "##{@order.guid} Shipment delivered") end end
require 'spec_helper' require 'yt/models/comment_thread' describe Yt::CommentThread do subject(:comment_thread) { Yt::CommentThread.new attrs } describe '#snippet' do context 'given fetching a comment thread returns a snippet' do let(:attrs) { {snippet: {"videoId" => "12345"}} } it { expect(comment_thread.snippet).to be_a Yt::Snippet } end end describe '#video_id' do context 'given a snippet with a video id' do let(:attrs) { {snippet: {"videoId"=>"12345"}} } it { expect(comment_thread.video_id).to eq '12345' } end context 'given a snippet without a video id' do let(:attrs) { {snippet: {}} } it { expect(comment_thread.video_id).to be_nil } end end describe '#top_level_comment' do context 'given a snippet with a top level comment' do let(:attrs) { {snippet: {"topLevelComment"=> {}}} } it { expect(comment_thread.top_level_comment).to be_a Yt::Comment } end end describe 'attributes from #top_level_comment delegations' do context 'with values' do let(:attrs) { {snippet: {"topLevelComment"=> {"id" => "xyz123", "snippet" => { "textDisplay" => "funny video!", "authorDisplayName" => "fullscreen", "likeCount" => 99, "updatedAt" => "2016-03-22T12:56:56.3Z"}}}} } it { expect(comment_thread.top_level_comment.id).to eq 'xyz123' } it { expect(comment_thread.text_display).to eq 'funny video!' } it { expect(comment_thread.author_display_name).to eq 'fullscreen' } it { expect(comment_thread.like_count).to eq 99 } it { expect(comment_thread.updated_at).to eq Time.parse('2016-03-22T12:56:56.3Z') } end context 'without values' do let(:attrs) { {snippet: {"topLevelComment"=> {"snippet" => {}}}} } it { expect(comment_thread.text_display).to be_nil } it { expect(comment_thread.author_display_name).to be_nil } it { expect(comment_thread.like_count).to be_nil } it { expect(comment_thread.updated_at).to be_nil } end end describe '#total_reply_count' do context 'given a snippet with a total reply count' do let(:attrs) { {snippet: {"totalReplyCount"=>1}} } it { expect(comment_thread.total_reply_count).to eq 1 } end context 'given a snippet without a total reply count' do let(:attrs) { {snippet: {}} } it { expect(comment_thread.total_reply_count).to be_nil } end end describe '#can_reply?' do context 'given a snippet with canReply set' do let(:attrs) { {snippet: {"canReply"=>true}} } it { expect(comment_thread.can_reply?).to be true } end context 'given a snippet without canReply set' do let(:attrs) { {snippet: {}} } it { expect(comment_thread.can_reply?).to be false } end end describe '#is_public?' do context 'given a snippet with isPublic set' do let(:attrs) { {snippet: {"isPublic"=>true}} } it { expect(comment_thread).to be_public } end context 'given a snippet without isPublic set' do let(:attrs) { {snippet: {}} } it { expect(comment_thread).to_not be_public } end end end
require "formula" class Makepkg < Formula homepage "https://wiki.archlinux.org/index.php/makepkg" url "ftp://ftp.archlinux.org/other/pacman/pacman-4.1.2.tar.gz" sha1 "ed9a40a9b532bc43e48680826d57518134132538" bottle do revision 1 sha1 "302edf1a558cd607e1747a7b25e5011678cde67e" => :mavericks sha1 "1044a51bec7287423cad12ad2816c0534a7788f0" => :mountain_lion sha1 "4908957c636158ed40fbdde85f6630df36469699" => :lion end depends_on "pkg-config" => :build depends_on "libarchive" => :build depends_on "bash" depends_on "fakeroot" def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}", "--sysconfdir=#{etc}" system "make", "install" end test do (testpath/"PKGBUILD").write("source=(https://androidnetworktester.googlecode.com/files/10kb.txt)") system "#{bin}/makepkg", "-dg" end end
# frozen_string_literal: true require 'rails_helper' feature '็ฎก็†็”ป้ข๏ผšๆ›ฒ่ฉณ็ดฐ๏ผšๅบƒๅ‘Š', js: true do let!(:user) { create(:user, :registered, :admin_user) } let!(:melody) { create(:melody, :with_season) } background do login(user) end context 'ๆ›ฒใซๅบƒๅ‘ŠใŒ็™ป้Œฒใ•ใ‚Œใฆใ„ใŸๅ ดๅˆ' do let!(:advertisement1) { create(:advertisement, melody: melody) } let!(:advertisement2) { create(:advertisement, melody: melody) } scenario 'ๆ›ฒ่ฉณ็ดฐ็”ป้ขใง่ฉฒๅฝ“ๆ›ฒใฎๅบƒๅ‘Šไธ€่ฆงใŒ่กจ็คบใ•ใ‚Œใ‚‹ใ“ใจ' do visit admin_melody_path(melody) within '.adminMelodyAdvertisementsComponent' do expect(page).to have_css "a[href='https://url.com']" expect(page).to have_content advertisement1.tag_name expect(page).to have_content advertisement2.tag_name end end scenario 'ๆ›ฒใฎๅบƒๅ‘Šใ‚’ๅ‰Š้™คใงใใ‚‹ใ“ใจ' do visit admin_melody_path(melody) within '.adminMelodyAdvertisementsComponent' do find("#advertisement-#{advertisement1.id}").hover within "#advertisement-#{advertisement1.id}" do find('.glyphicon-trash').click end end within '.modal-footer' do find('.btn-danger').click end expect(page).to have_no_css "#advertisement-#{advertisement1.id}" expect(page).to have_css "#advertisement-#{advertisement2.id}" expect(page).to have_content advertisement2.tag_name end end scenario 'ๆ›ฒใฎๅบƒๅ‘Šใ‚’็™ป้Œฒใงใใ‚‹ใ“ใจ' do visit admin_melody_path(melody) within '.adminMelodyAdvertisementsComponent' do find('.adminNewButtonFieldComponent').click end within '.adminMelodyAdvertisementNewFieldComponent' do fill_in 'tag_name', with: 'ๅบƒๅ‘Šใฎใ‚ฟใ‚ฐๅ' fill_in 'body', with: "<a href='https://example.com'>URL</a>" find('.btn-danger').click end within '.adminMelodyAdvertisementsComponent' do expect(page).to have_content 'URL' expect(page).to have_css "a[href='https://example.com']" expect(page).to have_content 'ๅบƒๅ‘Šใฎใ‚ฟใ‚ฐๅ' end end after do logout end end
# encoding: utf-8 # vim: ft=ruby expandtab shiftwidth=2 tabstop=2 packages = %w{git subversion zip unzip kernel-devel gcc perl make jq} packages.each do |pkg| package pkg do action [:install, :upgrade] end end git node[:wpcli][:dir] do repository "https://github.com/wp-cli/builds.git" action :sync end bin = ::File.join(node[:wpcli][:dir], 'phar', 'wp-cli.phar') file bin do mode '0755' action :create end link node[:wpcli][:link] do to bin end directory '/home/vagrant/.wp-cli' do recursive true owner node[:wpcli][:user] group node[:wpcli][:group] end directory '/home/vagrant/.wp-cli/commands' do recursive true owner node[:wpcli][:user] group node[:wpcli][:group] end template '/home/vagrant/.wp-cli/config.yml' do source "config.yml.erb" owner node[:wpcli][:user] group node[:wpcli][:group] mode "0644" variables( :docroot => File.join(node[:wpcli][:wp_docroot], node[:wpcli][:wp_siteurl]) ) end git 'home/vagrant/.wp-cli/commands/dictator' do repository "https://github.com/danielbachhuber/dictator.git" user node[:wpcli][:user] group node[:wpcli][:group] action :sync end
# Copyright ยฉ 2011-2019 MUSC Foundation for Research Development~ # All rights reserved.~ # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:~ # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.~ # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following~ # disclaimer in the documentation and/or other materials provided with the distribution.~ # 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products~ # derived from this software without specific prior written permission.~ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,~ # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT~ # SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL~ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS~ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR~ # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.~ require 'rails_helper' RSpec.describe '/associated_users/_user_form', type: :view do let_there_be_lane def render_user_form protocol = create(:unarchived_study_without_validations, id: 1, primary_pi: jug2, selected_for_epic: true) project_role = build(:project_role, id: 1, protocol_id: protocol.id, identity_id: jug2.id, role: 'consultant', epic_access: 0) service_request = build(:service_request_without_validations) dashboard = false assign(:user, jug2) render "/associated_users/user_form", header_text: "Edit Authorized User", identity: jug2, protocol: protocol, current_pi: jug2, project_role: project_role, dashboard: dashboard, service_request: service_request, admin: false end context 'When the user views the associated users form' do context 'epic configuration turned off' do stub_config("use_epic", false) it 'should show the correct header and labels' do render_user_form expect(response).to have_selector('h4', text: "Edit Authorized User") expect(response).to have_selector('label', text: t(:authorized_users)[:form_fields][:credentials]) expect(response).to have_selector('label', text: t(:authorized_users)[:form_fields][:institution]) expect(response).to have_selector('label', text: t(:authorized_users)[:form_fields][:college]) expect(response).to have_selector('label', text: t(:authorized_users)[:form_fields][:department]) expect(response).to have_selector('label', text: t(:authorized_users)[:form_fields][:phone]) expect(response).to have_selector('label', text: t(:authorized_users)[:form_fields][:role]) expect(response).to have_selector('label', text: t(:authorized_users)[:rights][:header]) expect(response).to have_selector('label', text: t(:authorized_users)[:form_fields][:college]) end it 'should show the correct buttons' do render_user_form expect(response).to have_selector('button', text: t(:actions)[:close]) expect(response).to have_selector('button', text: t(:actions)[:save]) expect(response).to have_selector('button.close') expect(response).to have_selector('button', count: 3) end it 'should show the correct form fields when not using epic and protocol is not selected for epic' do render_user_form expect(response).to have_selector('.radio', count: 3) expect(response).to have_selector('.radio-inline', count: 0) expect(response).not_to have_selector('label', text: 'No') expect(response).not_to have_selector('label', text: 'Yes') end end context 'epic configuration turned on' do stub_config("use_epic", true) it 'should show the correct form fields when using epic and protocol is selected for epic' do render_user_form expect(response).to have_selector('label', text: 'No') expect(response).to have_selector('label', text: 'Yes') expect(response).to have_selector('.radio-inline', count: 2) end end end end
require 'test_helper' require 'generators/ember/template_generator' class TemplateGeneratorTest < Rails::Generators::TestCase include GeneratorTestSupport tests Ember::Generators::TemplateGenerator destination File.join(Rails.root, "tmp") setup :prepare_destination test "generates template" do run_generator ["post"] assert_file "app/assets/javascripts/templates/post.hbs" end test "Assert files are properly created with custom path" do custom_path = ember_path("custom") run_generator [ "post", "-d", custom_path ] assert_file "#{custom_path}/templates/post.hbs" end test "Uses config.ember.ember_path" do custom_path = ember_path("custom") with_config ember_path: custom_path do run_generator ["post"] assert_file "#{custom_path}/templates/post.hbs" end end end
# :nodoc: module Validation def self.included(base) base.extend ClassMethods base.include InstanceMethods end # :nodoc: module ClassMethods attr_reader :params def validate(attr, type, template = nil) @params ||= [] @params << { attr: attr, type: type, template: template } end end # :nodoc: module InstanceMethods def validate! self.class.params.each do |h| attr = instance_variable_get("@#{h[:attr]}") # case h[:type] # when :presence # presence(attr) # when :format # format(attr, h[:template]) # when :type # type(attr, h[:template]) # end send((h[:type]).to_s, attr, h[:template]) end end def valid? validate! true rescue false end private def presence(attr, _not_use) raise ArgumentError, 'Attribute is nil' if attr.nil? raise ArgumentError, 'Attribute is empty' if attr == '' end def format(attr, form) raise ArgumentError, "Attribute's format is incorrect" unless attr.to_s =~ form end def type(attr, type) raise ArgumentError, "Attribute's type is incorrect" unless attr.class == type end end end # :TEST: # class Test # include Validation # attr_accessor :name # def initialize # @name = 'Dasha' # end # validate :name, :presence # puts "WER #{name.class}" # validate :name, :type, Integer # end