Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Add benchmark and working recursion solution | def is_prime?(num)
factors = []
range = (2..num-1).to_a
if num == 1
return false
elsif num == 2
return true
elsif lowest_factor(num) == nil
return true
else
range.each do | poss_factor |
if num % poss_factor == 0
factors << poss_factor
end
end
if factors.length == 0
return true
else
return false
end
end
end | require "benchmark"
def all_prime_factors_recursive(num, factors = [])
return nil if num == 1
return factors << num if is_prime?(num) # base case: breaks the recursion
# base case must be conditional
factors << lowest_factor(num)
num = num / lowest_factor(num)
all_prime_factors_recursive(num, factors) # the recursion
end
def is_prime?(num)
factors = []
range = (2..num-1).to_a
if num == 1
return false
elsif num == 2
return true
elsif lowest_factor(num) == nil
return true
else
range.each do | poss_factor |
if num % poss_factor == 0
factors << poss_factor
end
end
if factors.length == 0
return true
else
return false
end
end
end
def lowest_factor(num)
range = (2..num-1).to_a
return range.find { |poss_factor| (num % poss_factor) == 0 } #finds the first possible factor
end
puts Benchmark.measure{all_prime_factors_recursive(123123123)} |
Set RSpec 3.2 dependency since it supports failure_message_for_should and failure_message_for_should_not | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'rspec/matchers_test/version'
Gem::Specification.new do |spec|
spec.name = "rspec-matchers_test"
spec.version = Rspec::MatchersTest::VERSION
spec.authors = ["Simeon F. Willbanks"]
spec.email = ["simeon@simeons.net"]
spec.summary = %q{Testing RSpec matchers}
spec.description = %q{Testing RSpec matchers}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'rspec/matchers_test/version'
Gem::Specification.new do |spec|
spec.name = "rspec-matchers_test"
spec.version = Rspec::MatchersTest::VERSION
spec.authors = ["Simeon F. Willbanks"]
spec.email = ["simeon@simeons.net"]
spec.summary = %q{Testing RSpec matchers}
spec.description = %q{Testing RSpec matchers}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "3.2"
end
|
Handle start/end dates being blank | module ActiverecordChronologicalRecords
def has_chronological_records(*options)
if options.empty?
start_column, end_column = :start_date, :end_date
else
start_column, end_column = options[0], options[1]
end
self.instance_eval <<-EOS
def at(date)
where("#{start_column} <= :date AND (#{end_column} >= :date OR #{end_column} IS NULL)", :date => date)
end
def current
at(Time.now)
end
EOS
self.class_eval <<-EOS
def at(date)
#{self}.at(date).where(:#{primary_key} => self.#{primary_key}).first
end
def current
at(Time.now)
end
def current?
#{start_column}.to_time <= Time.now && #{end_column}.to_time >= Time.now
end
def earliest
#{self}.where(:#{primary_key} => self.#{primary_key}).order("#{start_column} ASC").first
end
def latest
#{self}.where(:#{primary_key} => self.#{primary_key}).order("#{start_column} DESC").first
end
def previous
at(#{start_column} - 1.day)
end
def next
at(#{end_column} + 1.day)
end
EOS
end
end
ActiveRecord::Base.extend ActiverecordChronologicalRecords | module ActiverecordChronologicalRecords
def has_chronological_records(*options)
if options.empty?
start_column, end_column = :start_date, :end_date
else
start_column, end_column = options[0], options[1]
end
self.instance_eval <<-EOS
def at(date)
where("(#{start_column} <= :date OR #{start_column} IS NULL) AND (#{end_column} >= :date OR #{end_column} IS NULL)", :date => date)
end
def current
at(Time.now)
end
EOS
self.class_eval <<-EOS
def at(date)
#{self}.at(date).where(:#{primary_key} => self.#{primary_key}).first
end
def current
at(Time.now)
end
def current?
(#{start_column}.blank? || #{start_column}.to_time <= Time.now) && (#{end_column}.blank? || #{end_column}.to_time >= Time.now)
end
def earliest
#{self}.where(:#{primary_key} => self.#{primary_key}).order("#{start_column} ASC").first
end
def latest
#{self}.where(:#{primary_key} => self.#{primary_key}).order("#{start_column} DESC").first
end
def previous
at(#{start_column} - 1.day)
end
def next
at(#{end_column} + 1.day)
end
EOS
end
end
ActiveRecord::Base.extend ActiverecordChronologicalRecords |
Fix counter issue on failing endorsement creation | class EndorsementsController < ApplicationController
respond_to :html
respond_to :json, only: :index
# GET /manifesto
def manifesto
@endorsements_counter = Endorsement.count
end
# GET /endorsements
# GET /endorsements.json
def index
@endorsement = Endorsement.new
@endorsements = Endorsement.visible.page params[:page]
@endorsements_counter = Endorsement.count
end
# POST /endorsements
def create
@endorsement = Endorsement.new endorsement_params
if @endorsement.save
redirect_to endorsements_url, notice: 'La teva signatura ha estat recollida. Gràcies pel teu suport.'
else
@endorsements = Endorsement.visible.page "1"
flash.now[:error] = 'Alguna de les dades introduïdes no és correcta. Revisa-les i torna a provar.'
render :index
end
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def endorsement_params
params.require(:endorsement).permit(
:name,
:lastname,
:doctype,
:docid,
:email,
:birthdate,
:postal_code,
:activity,
:subscribed,
:hidden
)
end
end
| class EndorsementsController < ApplicationController
respond_to :html
respond_to :json, only: :index
# GET /manifesto
def manifesto
@endorsements_counter = Endorsement.count
end
# GET /endorsements
# GET /endorsements.json
def index
@endorsement = Endorsement.new
@endorsements = Endorsement.visible.page params[:page]
@endorsements_counter = Endorsement.count
end
# POST /endorsements
def create
@endorsement = Endorsement.new endorsement_params
if @endorsement.save
redirect_to endorsements_url, notice: 'La teva signatura ha estat recollida. Gràcies pel teu suport.'
else
@endorsements = Endorsement.visible.page "1"
@endorsements_counter = Endorsement.count
flash.now[:error] = 'Alguna de les dades introduïdes no és correcta. Revisa-les i torna a provar.'
render :index
end
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def endorsement_params
params.require(:endorsement).permit(
:name,
:lastname,
:doctype,
:docid,
:email,
:birthdate,
:postal_code,
:activity,
:subscribed,
:hidden
)
end
end
|
Fix the source url in podspec file. | Pod::Spec.new do |s|
s.name = "StompClient"
s.version = "0.2.7"
s.summary = "Simple STOMP client."
s.description = "This project is a simple STOMP client, and we use Starscream as a websocket dependency."
s.homepage = "https://github.com/ShengHuaWu/StompClient"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "ShengHua Wu" => "fantasy0404@gmail.com" }
s.social_media_url = "https://twitter.com/ShengHuaWu"
s.platform = :ios, "9.0"
s.source = { :git => "https://github.com/vetikett/StompClient.git", :tag => s.version.to_s }
s.source_files = "StompClient/*.swift"
s.requires_arc = true
s.dependency "Starscream", "~> 2.0.0"
end
| Pod::Spec.new do |s|
s.name = "StompClient"
s.version = "0.2.7"
s.summary = "Simple STOMP client."
s.description = "This project is a simple STOMP client, and we use Starscream as a websocket dependency."
s.homepage = "https://github.com/ShengHuaWu/StompClient"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "ShengHua Wu" => "fantasy0404@gmail.com" }
s.social_media_url = "https://twitter.com/ShengHuaWu"
s.platform = :ios, "9.0"
s.source = { :git => "https://github.com/ShengHuaWu/StompClient.git", :tag => s.version.to_s }
s.source_files = "StompClient/*.swift"
s.requires_arc = true
s.dependency "Starscream", "~> 2.0.0"
end
|
Remove TODO related to future API call to create users | class InterviewsController < ApplicationController
before_action :find
def complete
if @interview.update completed: true
show_message :interview_complete,
default: 'Interview marked as completed.'
if params[:hired]
@interview.update hired: true
else
@interview.update hired: false,
interview_note: params[:interview_note]
end
# TODO: some kind of API call to create users.
redirect_to staff_dashboard_path
else show_errors @interview
end
end
def reschedule
params.require :scheduled
params.require :location
if @interview.update scheduled: params[:scheduled],
location: params[:location]
show_message :interview_reschedule,
default: 'Interview has been rescheduled.'
redirect_to staff_dashboard_path
else show_errors @interview
end
end
def show
respond_to do |format|
format.ics do
render 'interview.ics', layout: false
end
end
end
private
def find
params.require :id
@interview = Interview.find params[:id]
end
end
| class InterviewsController < ApplicationController
before_action :find
def complete
if @interview.update completed: true
show_message :interview_complete,
default: 'Interview marked as completed.'
if params[:hired]
@interview.update hired: true
else
@interview.update hired: false,
interview_note: params[:interview_note]
end
redirect_to staff_dashboard_path
else show_errors @interview
end
end
def reschedule
params.require :scheduled
params.require :location
if @interview.update scheduled: params[:scheduled],
location: params[:location]
show_message :interview_reschedule,
default: 'Interview has been rescheduled.'
redirect_to staff_dashboard_path
else show_errors @interview
end
end
def show
respond_to do |format|
format.ics do
render 'interview.ics', layout: false
end
end
end
private
def find
params.require :id
@interview = Interview.find params[:id]
end
end
|
Fix comments to allow yard to run | ##
# Outpost
require "outpost/engine"
require 'active_record'
require 'action_controller'
require 'outpost/config'
module Outpost
extend ActiveSupport::Autoload
autoload :Controller
autoload :Model
autoload :Hook
autoload :Helpers
autoload :List
autoload :Breadcrumb, 'outpost/breadcrumbs'
autoload :Breadcrumbs
#----------------------
class << self
attr_writer :config
def config
@config || Outpost::Config.configure
end
end
end
#----------------------
if defined?(ActiveRecord::Base)
ActiveRecord::Base.send :include, Outpost::Model
end
#----------------------
if defined?(ActionController::Base)
ActionController::Base.send :include, Outpost::Controller
end
| require "outpost/engine"
require 'active_record'
require 'action_controller'
require 'outpost/config'
module Outpost
extend ActiveSupport::Autoload
autoload :Controller
autoload :Model
autoload :Hook
autoload :Helpers
autoload :List
autoload :Breadcrumb, 'outpost/breadcrumbs'
autoload :Breadcrumbs
class << self
attr_writer :config
def config
@config || Outpost::Config.configure
end
end
end
if defined?(ActiveRecord::Base)
ActiveRecord::Base.send :include, Outpost::Model
end
if defined?(ActionController::Base)
ActionController::Base.send :include, Outpost::Controller
end
|
Remove reference for deleted file (control.rb) | require 'termnote/show/control'
require 'termnote/show/key'
module TermNote
class Show
attr_accessor :panes, :state
attr_writer :pane
def initialize
@panes ||= []
end
def add(pane)
raise ArgumentError, "Pane required" if pane.nil?
panes << pane
pane.show = self
end
def pane
@pane || panes.first
end
def position
panes.index pane
end
def total
panes.size
end
def start
@state = true
while @state
pane.call $stdout.winsize
Key.send @command, self if Key::KEYS.include? capture_command
end
end
def close
@state = false
end
def header
"[#{position + 1}/#{total}] - #{panes.first.title}\n".bold
end
def forward
@pane = panes[position + 1] || panes.first
end
def backward
@pane = panes[position - 1] || panes.last
end
private
def capture_command
@command = $stdin.getch
end
end
end
| require 'termnote/show/key'
module TermNote
class Show
attr_accessor :panes, :state
attr_writer :pane
def initialize
@panes ||= []
end
def add(pane)
raise ArgumentError, "Pane required" if pane.nil?
panes << pane
pane.show = self
end
def pane
@pane || panes.first
end
def position
panes.index pane
end
def total
panes.size
end
def start
@state = true
while @state
pane.call $stdout.winsize
Key.send @command, self if Key::KEYS.include? capture_command
end
end
def close
@state = false
end
def header
"[#{position + 1}/#{total}] - #{panes.first.title}\n".bold
end
def forward
@pane = panes[position + 1] || panes.first
end
def backward
@pane = panes[position - 1] || panes.last
end
private
def capture_command
@command = $stdin.getch
end
end
end
|
Add a failing test for undef params | require 'spec_helper'
describe 'openconnect' do
context 'supported operating systems' do
['Debian'].each do |osfamily|
describe "openconnect class without any parameters on #{osfamily}" do
let(:params) {{ }}
let(:facts) {{
:osfamily => osfamily,
}}
it { should include_class('openconnect::params') }
it { should contain_class('openconnect::install') }
it { should contain_class('openconnect::config') }
it { should contain_class('openconnect::service') }
end
end
end
context 'unsupported operating system' do
describe 'openconnect class without any parameters on CentOS/RedHat' do
let(:facts) {{
:osfamily => 'RedHat',
:operatingsystem => 'CentOS',
}}
it { expect { should }.to raise_error(Puppet::Error, /CentOS not supported/) }
end
end
end
| require 'spec_helper'
describe 'openconnect' do
context 'supported operating systems' do
['Debian'].each do |osfamily|
describe "openconnect class without any parameters on #{osfamily}" do
let(:params) {{ }}
let(:facts) {{
:osfamily => osfamily,
}}
it { should include_class('openconnect::params') }
it { should contain_class('openconnect::install') }
it { should contain_class('openconnect::config') }
it { should contain_class('openconnect::service') }
# FIXME
it 'should not allow required params to be bypassed' do
expect { should }.to raise_error(Puppet::Error, /Must pass/)
end
end
end
end
context 'unsupported operating system' do
describe 'openconnect class without any parameters on CentOS/RedHat' do
let(:facts) {{
:osfamily => 'RedHat',
:operatingsystem => 'CentOS',
}}
it { expect { should }.to raise_error(Puppet::Error, /CentOS not supported/) }
end
end
end
|
Remove failing code; "primitive Class" takes care of everything | module DataMapper
module Types
class Klass < DataMapper::Type
primitive Class
def self.load(value, property)
if value
value # value.is_a?(Class) ? value : Extlib::Inflection.constantize(value)
else
nil
end
end
def self.dump(value, property)
if value
(value.is_a? Class) ? value.name : Extlib::Inflection.constantize(value.to_s)
else
nil
end
end
end # class URI
end # module Types
end # module DataMapper
| module DataMapper
module Types
class Klass < DataMapper::Type
primitive Class
end # class Klass
end # module Types
end # module DataMapper
|
Use default_client following mongoid 5.0 | require 'database_cleaner/mongoid/base'
require 'database_cleaner/generic/truncation'
require 'database_cleaner/mongo/truncation_mixin'
require 'database_cleaner/mongo2/truncation_mixin'
require 'database_cleaner/moped/truncation_base'
require 'mongoid/version'
module DatabaseCleaner
module Mongoid
class Truncation
include ::DatabaseCleaner::Mongoid::Base
include ::DatabaseCleaner::Generic::Truncation
if ::Mongoid::VERSION < '3'
include ::DatabaseCleaner::Mongo::TruncationMixin
private
def database
::Mongoid.database
end
elsif ::Mongoid::VERSION < '5'
include ::DatabaseCleaner::Moped::TruncationBase
private
def session
::Mongoid.default_session
end
def database
if not(@db.nil? or @db == :default)
::Mongoid.databases[@db]
else
::Mongoid.database
end
end
else
include ::DatabaseCleaner::Mongo2::TruncationMixin
end
end
end
end
| require 'database_cleaner/mongoid/base'
require 'database_cleaner/generic/truncation'
require 'database_cleaner/mongo/truncation_mixin'
require 'database_cleaner/mongo2/truncation_mixin'
require 'database_cleaner/moped/truncation_base'
require 'mongoid/version'
module DatabaseCleaner
module Mongoid
class Truncation
include ::DatabaseCleaner::Mongoid::Base
include ::DatabaseCleaner::Generic::Truncation
if ::Mongoid::VERSION < '3'
include ::DatabaseCleaner::Mongo::TruncationMixin
private
def database
::Mongoid.database
end
elsif ::Mongoid::VERSION < '5'
include ::DatabaseCleaner::Moped::TruncationBase
private
def session
::Mongoid.default_client
end
def database
if not(@db.nil? or @db == :default)
::Mongoid.databases[@db]
else
::Mongoid.database
end
end
else
include ::DatabaseCleaner::Mongo2::TruncationMixin
end
end
end
end
|
Update uniform_notifier dependency to 1.10 | lib = File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
require "bullet/version"
Gem::Specification.new do |s|
s.name = "bullet"
s.version = Bullet::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Richard Huang"]
s.email = ["flyerhzm@gmail.com"]
s.homepage = "http://github.com/flyerhzm/bullet"
s.summary = "help to kill N+1 queries and unused eager loading."
s.description = "help to kill N+1 queries and unused eager loading."
s.license = 'MIT'
s.required_rubygems_version = ">= 1.3.6"
s.add_runtime_dependency "activesupport", ">= 3.0.0"
s.add_runtime_dependency "uniform_notifier", "~> 1.9.0"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_paths = ["lib"]
end
| lib = File.expand_path('../lib/', __FILE__)
$:.unshift lib unless $:.include?(lib)
require "bullet/version"
Gem::Specification.new do |s|
s.name = "bullet"
s.version = Bullet::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Richard Huang"]
s.email = ["flyerhzm@gmail.com"]
s.homepage = "http://github.com/flyerhzm/bullet"
s.summary = "help to kill N+1 queries and unused eager loading."
s.description = "help to kill N+1 queries and unused eager loading."
s.license = 'MIT'
s.required_rubygems_version = ">= 1.3.6"
s.add_runtime_dependency "activesupport", ">= 3.0.0"
s.add_runtime_dependency "uniform_notifier", "~> 1.10.0"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_paths = ["lib"]
end
|
Fix Gemfile ENV variable being reset | require 'rubygems'
gemfile = File.expand_path('../../../../Gemfile', __FILE__)
if File.exist?(gemfile)
ENV['BUNDLE_GEMFILE'] = gemfile
require 'bundler'
Bundler.setup
end
$:.unshift File.expand_path('../../../../lib', __FILE__) | require 'rubygems'
gemfile = File.expand_path('../../../../Gemfile', __FILE__)
if File.exist?(gemfile)
ENV['BUNDLE_GEMFILE'] ||= gemfile
require 'bundler'
Bundler.setup
end
$:.unshift File.expand_path('../../../../lib', __FILE__)
|
Remove not used attribute from spec | require 'spec_helper'
describe 'Defining public relations' do
let(:rom) { ROM.setup(sqlite: "sqlite::memory") }
before do
conn = rom.sqlite.connection
conn.run('create table tasks (title STRING, priority INT)')
conn[:tasks].insert(title: "be nice", priority: 1)
conn[:tasks].insert(title: "be cool", priority: 2)
rom.schema do
base_relation(:tasks) do
repository :sqlite
attribute :title, String
attribute :priority, Integer
attribute :created_at, DateTime
end
end
end
it 'allows to expose chainable relations' do
rom.relations do
tasks do
def high_priority
where { priority < 2 }
end
def by_title(title)
where(title: title)
end
end
end
tasks = rom.relations[:tasks]
expect(tasks.high_priority.by_title("be nice").to_a).to eql([title: "be nice", priority: 1])
expect(tasks.by_title("be cool").to_a).to eql([title: "be cool", priority: 2])
end
end
| require 'spec_helper'
describe 'Defining public relations' do
let(:rom) { ROM.setup(sqlite: "sqlite::memory") }
before do
conn = rom.sqlite.connection
conn.run('create table tasks (title STRING, priority INT)')
conn[:tasks].insert(title: "be nice", priority: 1)
conn[:tasks].insert(title: "be cool", priority: 2)
rom.schema do
base_relation(:tasks) do
repository :sqlite
attribute :title, String
attribute :priority, Integer
end
end
end
it 'allows to expose chainable relations' do
rom.relations do
tasks do
def high_priority
where { priority < 2 }
end
def by_title(title)
where(title: title)
end
end
end
tasks = rom.relations[:tasks]
expect(tasks.high_priority.by_title("be nice").to_a).to eql([title: "be nice", priority: 1])
expect(tasks.by_title("be cool").to_a).to eql([title: "be cool", priority: 2])
end
end
|
Test case for should download all | require 'test_helper'
class SearchControllerTest < ActionController::TestCase
include Devise::TestHelpers
test "should get index" do
sign_in User.first
get :index, nil, {current_project_id: Project.first.id}
assert_response :success
assert_not_nil assigns(:iczn_groups)
sign_out User.first
end
end
| require 'test_helper'
class SearchControllerTest < ActionController::TestCase
include Devise::TestHelpers
test "should get index" do
# Only signing in so that is_authenticated_user? doesn't fail
sign_in User.first
sign_out User.first
get :index, nil, {current_project_id: Project.first.id}
assert_response :success
assert_not_nil assigns(:iczn_groups)
end
test "should download all" do
i = IcznGroup.first
params = {download_all: '1',
select_all_traits: '1',
include_references: '1',
"#{i.name}[0]" => "#{i.id}",
format: :csv
}
post :results, params, {current_project_id: Project.first.id}
assert assigns :results
assert_response :success
assert_template 'search/results'
assert_equal @response.content_type, 'text/csv'
end
end
|
Use function for random block creation | #import the needed modules for communication with minecraft world
require_relative 'mcpi/minecraft'
# import needed block defintiions
require_relative 'mcpi/block'
# Create a connection to the Minecraft game
mc = Minecraft.create()
# Get the player position
playerPosition = mc.player.getTilePos()
# define the position of the bottom left block of the wall
blockXposn = playerPosition.x + 6
firstColumnX = blockXposn
blockYposn = playerPosition.y + 1
blockZposn = playerPosition.z + 6
# Create a wall using nested for loops
for row in 0...6
# increase the height of th current row to be built
blockYposn += 1
blockXposn = firstColumnX
for column in 0...10
#increase the distance along the row that the block is placed at
blockXposn += 1
#Generate a random number within the allowed range of colours (0 to 15 inclusive)
randomNumber = rand(16)
puts("random number to be used = #{randomNumber}")
puts("Creating block at (#{blockXposn}, #{blockYposn}, #{blockZposn})")
# Create a block
mc.setBlock(blockXposn, blockYposn, blockZposn, WOOL.withData(randomNumber))
sleep(0.5)
end
end
| #import the needed modules for communication with minecraft world
require_relative 'mcpi/minecraft'
# import needed block defintiions
require_relative 'mcpi/block'
# create a function to create a random block of wool
def getWoolBlockWithRandomColour()
#Generate a random number within the allowed range of colours (0 to 15 inclusive)
randomNumber = rand(16)
puts("random number to be used = #{randomNumber}")
block = WOOL.withData(randomNumber)
return block
end
# Create a connection to the Minecraft game
mc = Minecraft.create()
# Get the player position
playerPosition = mc.player.getTilePos()
# define the position of the bottom left block of the wall
blockXposn = playerPosition.x + 6
firstColumnX = blockXposn
blockYposn = playerPosition.y + 1
blockZposn = playerPosition.z + 6
# Create a wall using nested for loops
for row in 0...6
# increase the height of th current row to be built
blockYposn += 1
blockXposn = firstColumnX
for column in 0...10
#increase the distance along the row that the block is placed at
blockXposn += 1
puts("Creating block at (#{blockXposn}, #{blockYposn}, #{blockZposn})")
# Create a block
mc.setBlock(blockXposn, blockYposn, blockZposn, getWoolBlockWithRandomColour())
sleep(0.5)
end
end
|
Update ws client ids in reconnect. | class Sessions::Event::ChatStatusCustomer < Sessions::Event::ChatBase
def run
chat_id = 1
chat = Chat.find_by(id: chat_id)
if !chat
return {
event: 'chat_status_customer',
data: {
state: 'no_such_chat',
},
}
end
# check if it's a chat sessin reconnect
session_id = nil
if @data['data']['session_id']
session_id = @data['data']['session_id']
end
{
event: 'chat_status_customer',
data: chat.customer_state(session_id),
}
end
end
| class Sessions::Event::ChatStatusCustomer < Sessions::Event::ChatBase
def run
chat_id = 1
chat = Chat.find_by(id: chat_id)
if !chat
return {
event: 'chat_status_customer',
data: {
state: 'no_such_chat',
},
}
end
# check if it's a chat sessin reconnect
session_id = nil
if @data['data']['session_id']
session_id = @data['data']['session_id']
# update recipients of existing sessions
chat_session = Chat::Session.find_by(session_id: session_id)
chat_session.add_recipient(@client_id, true)
end
{
event: 'chat_status_customer',
data: chat.customer_state(session_id),
}
end
end
|
Add repository url to gemspec | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'seisan/version'
Gem::Specification.new do |spec|
spec.name = "seisan"
spec.version = Seisan::VERSION
spec.authors = ["SHIMADA Koji"]
spec.email = ["koji.shimada@enishi-tech.com"]
spec.description = %q{seisan solution for small team}
spec.summary = %q{seisan solution for small team}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "axlsx", "~> 2.0.1"
spec.add_runtime_dependency "gimlet", "~> 0.0.3"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'seisan/version'
Gem::Specification.new do |spec|
spec.name = "seisan"
spec.version = Seisan::VERSION
spec.authors = ["SHIMADA Koji"]
spec.email = ["koji.shimada@enishi-tech.com"]
spec.description = %q{seisan solution for small team}
spec.summary = %q{seisan solution for small team}
spec.homepage = "https://github.com/enishitech/seisan"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_runtime_dependency "axlsx", "~> 2.0.1"
spec.add_runtime_dependency "gimlet", "~> 0.0.3"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
end
|
Add WordPress Visual Form Builder XSS Scanner. | ##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
class Metasploit4 < Msf::Auxiliary
include Msf::HTTP::Wordpress
include Msf::Auxiliary::Scanner
include Msf::Auxiliary::Report
def initialize(info = {})
super(update_info(info,
'Name' => 'WordPress Visual Form Builder Plugin XSS Scanner',
'Description' => %q{
This module attempts to exploit a authenticated Cross-Site Scripting in Visual Form Builder
Plugin for Wordpress, version 2.8.2 and likely prior in order if the instance is vulnerable.
},
'Author' =>
[
'Tim Coen', # Vulnerability Discovery
'Roberto Soares Espreto <robertoespreto[at]gmail.com>' # Metasploit Module
],
'License' => MSF_LICENSE,
'References' =>
[
['WPVDB', '7991'],
['URL', 'http://software-talk.org/blog/2015/05/sql-injection-reflected-xss-visual-form-builder-wordpress-plugin/']
],
'DisclosureDate' => 'May 15 2015'
))
register_options(
[
OptString.new('WP_USER', [true, 'A valid username', nil]),
OptString.new('WP_PASSWORD', [true, 'Valid password for the provided username', nil])
], self.class)
end
def check
check_plugin_version_from_readme('visual-form-builder', '2.8.3')
end
def user
datastore['WP_USER']
end
def password
datastore['WP_PASSWORD']
end
def run_host(ip)
print_status("#{peer} - Trying to login as #{user}")
cookie = wordpress_login(user, password)
if cookie.nil?
print_error("#{peer} - Unable to login as #{user}")
return
end
print_good("#{peer} - Login successful")
xss = Rex::Text.rand_text_numeric(8)
xss_payload = '><script>alert(' + "#{xss}" + ');</script>'
res = send_request_cgi(
'uri' => normalize_uri(wordpress_url_backend, 'admin.php'),
'vars_get' => {
'page' => 'visual-form-builder',
's' => "#{xss_payload}"
},
'cookie' => cookie
)
unless res && res.body
print_error("#{peer} - Server did not respond in an expected way")
return
end
if res.code == 200 && res.body =~ /#{xss}/
print_good("#{peer} - Vulnerable to Cross-Site Scripting the \"Visual Form Builder 2.8.2\" plugin for Wordpress")
p = store_local('wp_visualform.http', 'text/html', res.body, "#{xss}")
print_good("Save in: #{p}")
else
print_error("#{peer} - Failed, maybe the target isn't vulnerable.")
end
end
end
| |
Make maps listing public in API | # frozen_string_literal: true
module Api
class MapsController < Api::ApplicationController
def index
@maps = MapUpload.available_maps
@cloud_maps = MapUpload.available_cloud_maps
end
end
end
| # frozen_string_literal: true
module Api
class MapsController < Api::ApplicationController
skip_before_action :verify_api_key
def index
@maps = MapUpload.available_maps
@cloud_maps = MapUpload.available_cloud_maps
end
end
end
|
Set Content API web URLs relative to the website root | require 'gds_api/helpers'
class ApplicationController < ActionController::Base
include GdsApi::Helpers
include Slimmer::Headers
protect_from_forgery with: :exception
private
def error_404; error 404; end
def error_410; error 410; end
def error_503(e); error(503, e); end
def error(status_code, exception = nil)
render status: status_code, text: "#{status_code} error"
end
def cacheable_404
set_expiry(10.minutes)
error 404
end
def set_expiry(duration = 30.minutes)
unless Rails.env.development?
expires_in(duration, :public => true)
end
end
def validate_slug_param(param_name = :slug)
param_to_use = params[param_name]
if param_to_use.parameterize != param_to_use
cacheable_404
end
rescue StandardError # Triggered by trying to parameterize malformed UTF-8
cacheable_404
end
end
| require 'gds_api/content_api'
class ApplicationController < ActionController::Base
include Slimmer::Headers
protect_from_forgery with: :exception
private
def error_404; error 404; end
def error_410; error 410; end
def error_503(e); error(503, e); end
def error(status_code, exception = nil)
render status: status_code, text: "#{status_code} error"
end
def cacheable_404
set_expiry(10.minutes)
error 404
end
def set_expiry(duration = 30.minutes)
unless Rails.env.development?
expires_in(duration, :public => true)
end
end
def validate_slug_param(param_name = :slug)
param_to_use = params[param_name]
if param_to_use.parameterize != param_to_use
cacheable_404
end
rescue StandardError # Triggered by trying to parameterize malformed UTF-8
cacheable_404
end
def content_api
@content_api ||= GdsApi::ContentApi.new(
Plek.current.find('contentapi'),
{ web_urls_relative_to: Plek.current.website_root }
)
end
end
|
Update gemspec with better descriptions of the gem | $LOAD_PATH.unshift File.expand_path("../lib", __FILE__)
require "importu/version"
Gem::Specification.new do |s|
s.name = "importu"
s.version = Importu::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Daniel Hedlund"]
s.email = ["daniel@digitree.org"]
s.homepage = "https://github.com/dhedlund/importu"
s.summary = "A framework for importing data"
s.description = "Importu is a framework for importing data"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_paths = ["lib"]
s.licenses = ["MIT"]
s.add_dependency "multi_json", ["~> 1.0"]
s.add_dependency "nokogiri"
s.add_development_dependency "bundler", [">= 1.0.0"]
s.add_development_dependency "rspec", ["~> 3.6"]
s.add_development_dependency "rdoc", [">= 0"]
s.add_development_dependency "simplecov", ["~> 0.14"]
s.add_development_dependency "appraisal"
end
| $LOAD_PATH.unshift File.expand_path("../lib", __FILE__)
require "importu/version"
Gem::Specification.new do |s|
s.name = "importu"
s.version = Importu::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Daniel Hedlund"]
s.email = ["daniel@digitree.org"]
s.homepage = "https://github.com/dhedlund/importu"
s.summary = "Because an import should be defined by a contract, not " +
"a sequence of commands"
s.description = "Importu simplifies the process of defining and sharing " +
"contracts that structured data must conform to in order " +
"to be importable into your application."
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_paths = ["lib"]
s.licenses = ["MIT"]
s.add_dependency "multi_json", ["~> 1.0"]
s.add_dependency "nokogiri"
s.add_development_dependency "bundler", [">= 1.0.0"]
s.add_development_dependency "rspec", ["~> 3.6"]
s.add_development_dependency "rdoc", [">= 0"]
s.add_development_dependency "simplecov", ["~> 0.14"]
s.add_development_dependency "appraisal"
end
|
Enable use of "writable?" helper without gallery set. | module GalleriesHelper
def writable?
!(@gallery.read_only && !@boss_token)
end
end
| module GalleriesHelper
def writable?
@gallery && !(@gallery.read_only && !@boss_token)
end
end
|
Add simple tests for CorkHelper; | require 'nabokov/helpers/cork_helper'
describe Nabokov::CorkHelper do
let(:ui) { object_double(Cork::Board.new(silent: true, verbose: true)) }
describe "show_prompt" do
it "prints bold greed symbol" do
expect(ui).to receive(:print).with("> ".bold.green)
Nabokov::CorkHelper.new(ui).show_prompt
end
end
describe "say" do
it "prints plain message" do
expect(ui).to receive(:puts).with("Hey!")
Nabokov::CorkHelper.new(ui).say("Hey!")
end
end
describe "inform" do
it "prints green message" do
expect(ui).to receive(:puts).with("Nabokov is working".green)
Nabokov::CorkHelper.new(ui).inform("Nabokov is working")
end
end
describe "error" do
it "prints red message" do
expect(ui).to receive(:puts).with("Something went wrong".red)
Nabokov::CorkHelper.new(ui).error("Something went wrong")
end
end
end
| |
Modify cnvas_rake file for pact | require 'pact_broker/client/tasks'
# see https://github.com/pact-foundation/pact_broker-client/blob/master/README.md
namespace :broker do
PactBroker::Client::PublicationTask.new(:local) do |task|
format_rake_task(
task,
'http://pact-broker.docker',
'pact',
'broker',
'local'
)
end
PactBroker::Client::PublicationTask.new(:jenkins_post_merge) do |task|
format_rake_task(
task,
ENV.fetch('PACT_BROKER_BASE_URL'),
ENV.fetch('PACT_BROKER_BASIC_AUTH_USERNAME'),
ENV.fetch('PACT_BROKER_BASIC_AUTH_PASSWORD'),
'master'
)
end
def format_rake_task(task, url, username, password, task_tag)
require 'quiz_api_client'
task.consumer_version = CanvasApiClient::VERSION
task.pattern = 'pacts/*.json'
task.pact_broker_base_url = url
task.pact_broker_basic_auth = { username: username, password: password }
task.tag = task_tag
puts "Pact file tagged with: #{task.tag}"
end
end
| require 'pact_broker/client/tasks'
# see https://github.com/pact-foundation/pact_broker-client/blob/master/README.md
namespace :broker do
PactBroker::Client::PublicationTask.new(:local) do |task|
format_rake_task(
task,
'http://pact-broker.docker',
'pact',
'broker',
'local'
)
end
PactBroker::Client::PublicationTask.new(:jenkins_post_merge) do |task|
format_rake_task(
task,
ENV.fetch('PACT_BROKER_HOST'),
ENV.fetch('PACT_BROKER_USERNAME'),
ENV.fetch('PACT_BROKER_PASSWORD'),
'master'
)
end
def format_rake_task(task, url, username, password, task_tag)
task.consumer_version = CanvasApiClient::VERSION
task.pattern = 'pacts/*.json'
task.pact_broker_base_url = url
task.pact_broker_basic_auth = { username: username, password: password }
task.tag = task_tag
puts "Pact file tagged with: #{task.tag}"
end
end
|
Include google events scripts in dev environment | module GoogleClosureHelper
def closure_include_tag(file_path)
out = ''
unless ActionController::Base.perform_caching
closure_base_path = File.join(GoogleClosureCompiler.closure_library_path, 'goog')
out << "<script src='#{File.join('/javascripts', closure_base_path, 'base.js')}' type='text/javascript'></script>"
end
out << javascript_include_tag(file_path, :cache => "cache/closure/#{file_path.delete('.js')}")
out
end
end | module GoogleClosureHelper
def closure_include_tag(file_path)
out = ''
unless ActionController::Base.perform_caching
closure_base_path = File.join(GoogleClosureCompiler.closure_library_path, 'goog')
out << "<script src='#{File.join('/javascripts', closure_base_path, 'base.js')}' type='text/javascript'></script>"
out << "<script type='text/javascript'>goog.require('goog.events');</script>"
end
out << javascript_include_tag(file_path, :cache => "cache/closure/#{file_path.delete('.js')}")
out
end
end |
Fix assignment order in button_link_to | # frozen_string_literal: true
module ApplicationHelper
def duration_of_time_in_words(secs)
distance_of_time_in_words(0, secs, include_seconds: true)
end
def button_link_to(name = nil, options = {}, html_options = {}, &block)
if block_given?
name = capture(&block)
options = name
html_options = options
end
html_options[:class] ||= ""
html_options[:class] += " btn btn-default"
if html_options[:disabled]
content_tag(:span, name, html_options)
else
link_to(name, options, html_options)
end
end
def bs_nav_link(text, url)
content_tag(:li, link_to(text, url), class: ("active" if current_page?(url)))
end
def language_name_with_icon(key, options = {})
l = Morph::Language.new(key)
image_tag(l.image_path, options) + " " + l.human
end
end
| # frozen_string_literal: true
module ApplicationHelper
def duration_of_time_in_words(secs)
distance_of_time_in_words(0, secs, include_seconds: true)
end
def button_link_to(name = nil, options = {}, html_options = {}, &block)
if block_given?
html_options = options
options = name
name = capture(&block)
end
html_options[:class] ||= ""
html_options[:class] += " btn btn-default"
if html_options[:disabled]
content_tag(:span, name, html_options)
else
link_to(name, options, html_options)
end
end
def bs_nav_link(text, url)
content_tag(:li, link_to(text, url), class: ("active" if current_page?(url)))
end
def language_name_with_icon(key, options = {})
l = Morph::Language.new(key)
image_tag(l.image_path, options) + " " + l.human
end
end
|
Remove quantity and unit columns for migration after | # This migration comes from planning_engine (originally 20180423074302)
class CreateInterventionProposalParameters < ActiveRecord::Migration
def change
create_table :intervention_proposal_parameters do |t|
t.references :intervention_proposal, index: { name: :intervention_proposal_parameter_id }, foreign_key: true
t.references :product, index: true, foreign_key: true
t.references :product_nature_variant, index: { name: :intervention_product_nature_variant_id }, foreign_key: true
t.string :product_type
t.decimal :quantity
t.string :unit
t.timestamps null: false
end
end
end
| # This migration comes from planning_engine (originally 20180423074302)
class CreateInterventionProposalParameters < ActiveRecord::Migration
def change
create_table :intervention_proposal_parameters do |t|
t.references :intervention_proposal, index: { name: :intervention_proposal_parameter_id }, foreign_key: true
t.references :product, index: true, foreign_key: true
t.references :product_nature_variant, index: { name: :intervention_product_nature_variant_id }, foreign_key: true
t.string :product_type
t.timestamps null: false
end
end
end
|
Add description and summary to gemspec | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'capybara_wysihtml5/version'
Gem::Specification.new do |spec|
spec.name = "capybara_wysihtml5"
spec.version = CapybaraWysihtml5::VERSION
spec.authors = ["Miles Z. Sterrett"]
spec.email = ["miles@mileszs.com"]
spec.description = %q{TODO: Write a gem description}
spec.summary = %q{TODO: Write a gem summary}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'capybara_wysihtml5/version'
Gem::Specification.new do |spec|
spec.name = "capybara_wysihtml5"
spec.version = CapybaraWysihtml5::VERSION
spec.authors = ["Miles Z. Sterrett"]
spec.email = ["miles@mileszs.com"]
spec.description = %q{Interact with wysihtml5 text areas with capyabara}
spec.summary = %q{Interact with wysihtml5 text areas with capyabara}
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
end
|
Change ip_free? method to work in multiple OS | require 'active_attr'
module Bebox
class Server
include ActiveAttr::Model
attribute :ip
attribute :hostname
attr_accessor :ip, :hostname
I18n.enforce_available_locales = false
def ip_free?
pattern = Regexp.new("Destination Host Unreachable")
ip_is_available =false
`ping #{ip} -c 1 >> 'tmp/#{ip}_ping.log'`
file = File.read("tmp/#{ip}_ping.log")
file.each_line do |line|
if line.match(pattern)
ip_is_available = true
break
end
end
errors.add(:ip, 'is already taken!') unless ip_is_available
remove_logs
ip_is_available
end
def valid?
ip_free? && valid_hostname?
end
def remove_logs
`rm tmp/*_ping.log`
end
def valid_hostname?
# reg server1.project_name.environment
true
end
end
end | require 'active_attr'
module Bebox
class Server
include ActiveAttr::Model
attribute :ip
attribute :hostname
attr_accessor :ip, :hostname
I18n.enforce_available_locales = false
def ip_free?
`ping -q -c 1 #{ip}`
ip_is_available = ($?.exitstatus == 0) ? false : true
errors.add(:ip, 'is already taken!') unless ip_is_available
ip_is_available
end
def valid?
ip_free? && valid_hostname?
end
def valid_hostname?
# reg server1.project_name.environment
true
end
end
end |
Fix problems transitioning from insecure_private_key to less_insecure_private_key (Vagrant >= 1.4.0) |
require 'vagrant/util/subprocess'
require "vagrant-rekey-ssh/helpers"
module VagrantPlugins
module RekeySSH
class ActionSSHInfo
def initialize(app, env)
@app = app
@env = env
@machine = env[:machine]
end
def call(env)
if @machine.config.rekey_ssh.enable
# ensure we have a key
generate_ssh_key
# if the user's config hasn't specified a key, then set our key
# in here. We also specify the insecure key too so that it works
# in case we haven't replaced the key yet.
# -> TODO: only specify the insecure key when we haven't set the
# less insecure key on the box.
if @machine.config.ssh.private_key_path.nil?
if ::File.exists?(rekey_sentinel_file)
if Vagrant::VERSION < "1.4.0"
@machine.config.ssh.private_key_path = ssh_key_path
else
@machine.config.ssh.private_key_path = [ssh_key_path]
end
end
# Vagrant < 1.4 only supports a single ssh key, do this differently
#if Vagrant::VERSION <= "1.4.0"
#else
# @machine.config.ssh.private_key_path = [ssh_key_path, @machine.env.default_private_key_path]
#end
end
end
@app.call(env)
end
protected
include VagrantPlugins::RekeySSH::Helpers
end
end
end
|
require 'vagrant/util/subprocess'
require "vagrant-rekey-ssh/helpers"
module VagrantPlugins
module RekeySSH
class ActionSSHInfo
def initialize(app, env)
@app = app
@env = env
@machine = env[:machine]
end
def call(env)
if @machine.config.rekey_ssh.enable
# ensure we have a key
generate_ssh_key
# if the user's config hasn't specified a key, then set our key
# in here. We also specify the insecure key too so that it works
# in case we haven't replaced the key yet.
# -> TODO: only specify the insecure key when we haven't set the
# less insecure key on the box.
if @machine.config.ssh.private_key_path.nil?
if ::File.exists?(rekey_sentinel_file)
if Vagrant::VERSION < "1.4.0"
@machine.config.ssh.private_key_path = ssh_key_path
else
@machine.config.ssh.private_key_path = [ssh_key_path, @machine.env.default_private_key_path]
end
end
# Vagrant < 1.4 only supports a single ssh key, do this differently
#if Vagrant::VERSION <= "1.4.0"
#else
# @machine.config.ssh.private_key_path = [ssh_key_path, @machine.env.default_private_key_path]
#end
end
end
@app.call(env)
end
protected
include VagrantPlugins::RekeySSH::Helpers
end
end
end
|
Fix typo 'start' -> 'stop' | require_relative '../shared'
require_relative '../../script/script'
module Zlown::CLI
desc 'Manage scripts'
command 'script' do |c|
c.desc 'Manage httpry'
c.command 'httpry' do |cmd|
cmd.desc 'Start httpry'
cmd.command 'start' do |script_cmd|
script_cmd.action do |global_options, options, args|
Zlown::Script.httpry_start(args, options)
end
end
cmd.desc 'Stop httpry'
cmd.command 'start' do |script_cmd|
script_cmd.action do |global_options, options, args|
Zlown::Script.httpry_stop(args, options)
end
end
end
end
end
| require_relative '../shared'
require_relative '../../script/script'
module Zlown::CLI
desc 'Manage scripts'
command 'script' do |c|
c.desc 'Manage httpry'
c.command 'httpry' do |cmd|
cmd.desc 'Start httpry'
cmd.command 'start' do |script_cmd|
script_cmd.action do |global_options, options, args|
Zlown::Script.httpry_start(args, options)
end
end
cmd.desc 'Stop httpry'
cmd.command 'stop' do |script_cmd|
script_cmd.action do |global_options, options, args|
Zlown::Script.httpry_stop(args, options)
end
end
end
end
end
|
Use pluck for better performance | module Bidu
module House
class ErrorReport
include JsonParser
attr_reader :json
json_parse :threshold, type: :float
json_parse :period, type: :period
json_parse :scope, :id, :clazz, :external_key, case: :snake
def initialize(options)
@json = {
external_key: :id,
threshold: 0.02,
period: 1.day,
scope: :with_error
}.merge(options)
end
def status
@status ||= error? ? :error : :ok
end
def percentage
@percentage ||= last_entires.percentage(scope)
end
def scoped
@scoped ||= last_entires.public_send(scope)
end
def error?
percentage > threshold
end
def as_json
{
ids: scoped.map(&external_key),
percentage: percentage
}
end
private
def last_entires
@last_entires ||= clazz.where('updated_at >= ?', period.seconds.ago)
end
end
end
end | module Bidu
module House
class ErrorReport
include JsonParser
attr_reader :json
json_parse :threshold, type: :float
json_parse :period, type: :period
json_parse :scope, :id, :clazz, :external_key, case: :snake
def initialize(options)
@json = {
external_key: :id,
threshold: 0.02,
period: 1.day,
scope: :with_error
}.merge(options)
end
def status
@status ||= error? ? :error : :ok
end
def percentage
@percentage ||= last_entires.percentage(scope)
end
def scoped
@scoped ||= last_entires.public_send(scope)
end
def error?
percentage > threshold
end
def as_json
{
ids: scoped.pluck(external_key),
percentage: percentage
}
end
private
def last_entires
@last_entires ||= clazz.where('updated_at >= ?', period.seconds.ago)
end
end
end
end |
Add example of creating moip account with company | # Here is an example of creating an Moip account using the Moip account API
auth = Moip2::Auth::OAuth.new("502f9ca0eccc451dbcf8c0b940110af1_v2")
client = Moip2::Client.new(:sandbox, auth)
api = Moip2::Api.new(client)
account = api.accounts.create(
email: {
address: "dev.moip@labs.moip.com.br",
},
person: {
name: "Joaquim José",
lastName: "Silva Silva",
taxDocument: {
type: "CPF",
number: "978.443.610-85",
},
identityDocument: {
type: "RG",
number: "35.868.057-8",
issuer: "SSP",
issueDate: "2000-12-12",
},
birthDate: "1990-01-01",
phone: {
countryCode: "55",
areaCode: "11",
number: "965213244",
},
address: {
street: "Av. Brigadeiro Faria Lima",
streetNumber: "2927",
district: "Itaim",
zipCode: "01234-000",
city: "S\u00E3o Paulo",
state: "SP",
country: "BRA",
},
},
company: {
name: "Company Test",
businessName: "Razão Social Test",
address: {
street: "Av. Brigadeiro Faria Lima",
streetNumber: "4530",
district: "Itaim",
city: "São Paulo",
state: "SP",
country: "BRA",
zipCode: "01234000",
},
mainActivity: {
cnae: "82.91-1/00",
description: "Atividades de cobranças e informações cadastrais",
},
taxDocument: {
type: "CNPJ",
number: "61.148.461/0001-09",
},
phone: {
countryCode: "55",
areaCode: "11",
number: "975142244",
},
},
type: "MERCHANT",
)
| |
Fix SQL query syntax so we get agents and admins | class User < ActiveRecord::Base
has_many :tickets
has_many :comments
before_create :set_default_role
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :first_name, :last_name, :password, :password_confirmation, :remember_me
scope :agents, where("role = ? OR ?", "agent", "admin")
scope :admins, where(:role => "admin")
ROLES = %w[customer agent admin]
def self.default_agent
# TODO: Make this configurable in the app
User.agents.first
end
def name
return [self.first_name, self.last_name].join(" ").lstrip
end
def to_s
if self.name.to_s.empty?
return self.email
else
return self.name
end
end
def role?(base_role)
ROLES.index(base_role.to_s) <= ROLES.index(role)
end
private
def set_default_role
self.role = ROLES[0]
end
end
| class User < ActiveRecord::Base
has_many :tickets
has_many :comments
before_create :set_default_role
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :first_name, :last_name, :password, :password_confirmation, :remember_me
scope :agents, where("role = ? OR role = ?", "agent", "admin")
scope :admins, where(:role => "admin")
ROLES = %w[customer agent admin]
def self.default_agent
# TODO: Make this configurable in the app
User.agents.first
end
def name
return [self.first_name, self.last_name].join(" ").lstrip
end
def to_s
if self.name.to_s.empty?
return self.email
else
return self.name
end
end
def role?(base_role)
ROLES.index(base_role.to_s) <= ROLES.index(role)
end
private
def set_default_role
self.role = ROLES[0]
end
end
|
Write the registrations spec with rspec | require 'rails_helper'
describe Auth::RegistrationsController do
let(:valid_session) { {} }
describe 'POST #create' do
before :each do
request.env['devise.mapping'] = Devise.mappings[:user]
end
it 'defaults admin to false when omitted' do
post :create, user: {
username: 'portus',
email: 'portus@test.com',
password: '12341234',
'password_confirmation': '12341234'
}
assert !User.find_by!(username: 'portus').admin
end
it 'handles the admin column properly' do
post :create, user: {
username: 'portus',
email: 'portus@test.com',
password: '12341234',
'password_confirmation': '12341234',
admin: true
}
assert User.find_by!(username: 'portus').admin
end
it 'omits the value of admin if there is already another admin' do
create(:user, admin: true)
post :create, user: {
username: 'portus',
email: 'portus@test.com',
password: '12341234',
'password_confirmation': '12341234',
admin: true
}
assert !User.find_by!(username: 'portus').admin
end
end
end
| require 'rails_helper'
describe Auth::RegistrationsController do
let(:valid_session) { {} }
describe 'POST #create' do
before :each do
request.env['devise.mapping'] = Devise.mappings[:user]
end
it 'defaults admin to false when omitted' do
post :create, user: {
username: 'portus',
email: 'portus@test.com',
password: '12341234',
'password_confirmation': '12341234'
}
expect(User.find_by!(username: 'portus')).not_to be_admin
end
it 'handles the admin column properly' do
post :create, user: {
username: 'portus',
email: 'portus@test.com',
password: '12341234',
'password_confirmation': '12341234',
admin: true
}
expect(User.find_by!(username: 'portus')).to be_admin
end
it 'omits the value of admin if there is already another admin' do
create(:user, admin: true)
post :create, user: {
username: 'portus',
email: 'portus@test.com',
password: '12341234',
'password_confirmation': '12341234',
admin: true
}
expect(User.find_by!(username: 'portus')).not_to be_admin
end
end
end
|
Add a test for runit-systemd and use the process inspec resource | describe package('runit') do
it { should be_installed }
end
describe command('ps -ef | grep -v grep | grep "runsvdir"') do
its(:exit_status) { should eq 0 }
its(:stdout) { should match(/runsvdir/) }
end
describe file('/etc/service') do
it { should be_directory }
its('mode') { should cmp '0755' }
it { should be_owned_by 'root' }
it { should be_grouped_into 'root' }
end
| if os[:family] == 'debian' && os[:release].to_i == 9
describe package('runit-systemd') do
it { should be_installed }
end
end
describe package('runit') do
it { should be_installed }
end
describe processes('runsvdir') do
it { should exist }
end
describe file('/etc/service') do
it { should be_directory }
its('mode') { should cmp '0755' }
it { should be_owned_by 'root' }
it { should be_grouped_into 'root' }
end
|
Use abstract matcher rather than regex | module MethodFound
class Interceptor < Module
attr_reader :regex
def initialize(regex = nil, &intercept_block)
define_method_missing(regex, &intercept_block) unless regex.nil?
end
def define_method_missing(regex, &intercept_block)
@regex = regex
intercept_method = assign_intercept_method(&intercept_block)
method_cacher = method(:cache_method)
define_method :method_missing do |method_name, *arguments, &method_block|
if matches = regex.match(method_name)
method_cacher.(method_name, matches)
send(method_name, *arguments, &method_block)
else
super(method_name, *arguments, &method_block)
end
end
define_method :respond_to_missing? do |method_name, include_private = false|
(method_name =~ regex) || super(method_name, include_private)
end
end
def inspect
klass = self.class
name = klass.name || klass.inspect
"#<#{name}: #{regex.inspect}>"
end
private
def cache_method(method_name, matches)
intercept_method = @intercept_method
define_method method_name do |*arguments, &block|
send(intercept_method, method_name, matches, *arguments, &block)
end
end
def assign_intercept_method(&intercept_block)
@intercept_method ||= "__intercept_#{SecureRandom.hex}".freeze.tap do |method_name|
define_method method_name, &intercept_block
end
end
end
end
| module MethodFound
class Interceptor < Module
attr_reader :matcher
def initialize(regex = nil, &intercept_block)
define_method_missing(regex, &intercept_block) unless regex.nil?
end
def define_method_missing(matcher, &intercept_block)
@matcher = matcher
intercept_method = assign_intercept_method(&intercept_block)
method_cacher = method(:cache_method)
define_method :method_missing do |method_name, *arguments, &method_block|
if matches = matcher.match(method_name)
method_cacher.(method_name, matches)
send(method_name, *arguments, &method_block)
else
super(method_name, *arguments, &method_block)
end
end
define_method :respond_to_missing? do |method_name, include_private = false|
matcher.match(method_name) || super(method_name, include_private)
end
end
def inspect
klass = self.class
name = klass.name || klass.inspect
"#<#{name}: #{matcher.inspect}>"
end
private
def cache_method(method_name, matches)
intercept_method = @intercept_method
define_method method_name do |*arguments, &block|
send(intercept_method, method_name, matches, *arguments, &block)
end
end
def assign_intercept_method(&intercept_block)
@intercept_method ||= "__intercept_#{SecureRandom.hex}".freeze.tap do |method_name|
define_method method_name, &intercept_block
end
end
end
end
|
Check assumption that name = '' for root | require 'chef_fs/path_utils'
module ChefFS
module FileSystem
class BaseFSObject
def initialize(name, parent)
@parent = parent
if parent
@name = name
@path = ChefFS::PathUtils::join(parent.path, name)
else
@path = '/'
end
end
attr_reader :name
attr_reader :parent
attr_reader :path
def root
parent ? parent.root : self
end
def path_for_printing
if parent
ChefFS::PathUtils::join(parent.path_for_printing, name)
else
name
end
end
def dir?
false
end
def exists?
true
end
def content_type
:text
end
# Important directory attributes: name, parent, path, root
# Overridable attributes: dir?, child(name), path_for_printing
# Abstract: read, write, delete, children
end
end
end
| require 'chef_fs/path_utils'
module ChefFS
module FileSystem
class BaseFSObject
def initialize(name, parent)
@parent = parent
if parent
@name = name
@path = ChefFS::PathUtils::join(parent.path, name)
else
if name != ''
raise ArgumentError, "Name of root object must be empty string: was '#{name}' instead"
end
@path = '/'
end
end
attr_reader :name
attr_reader :parent
attr_reader :path
def root
parent ? parent.root : self
end
def path_for_printing
if parent
ChefFS::PathUtils::join(parent.path_for_printing, name)
else
name
end
end
def dir?
false
end
def exists?
true
end
def content_type
:text
end
# Important directory attributes: name, parent, path, root
# Overridable attributes: dir?, child(name), path_for_printing
# Abstract: read, write, delete, children
end
end
end
|
Upgrade 'Navicat for MySQL.app' to v11.1.10 | cask :v1 => 'navicat-for-mysql' do
version '11.1.9' # navicat-premium.rb and navicat-for-* should be upgraded together
sha256 'dcb8e15b134bda9b7c416fac54bd4e1d233cf31f8f6f9443a530dffc0adf732e'
url "http://download.navicat.com/download/navicat#{version.sub(%r{^(\d+)\.(\d+).*},'\1\2')}_mysql_en.dmg"
name 'Navicat for MySQL'
homepage 'http://www.navicat.com/products/navicat-for-mysql'
license :commercial
tags :vendor => 'Navicat'
app 'Navicat for MySQL.app'
end
| cask :v1 => 'navicat-for-mysql' do
version '11.1.10' # navicat-premium.rb and navicat-for-* should be upgraded together
sha256 '5e7ae59235e67547c2deacc2fa1b45dc4bfa4fef5f25ac4fff901df3bfaa9821'
url "http://download.navicat.com/download/navicat#{version.sub(%r{^(\d+)\.(\d+).*},'\1\2')}_mysql_en.dmg"
name 'Navicat for MySQL'
homepage 'http://www.navicat.com/products/navicat-for-mysql'
license :commercial
tags :vendor => 'Navicat'
app 'Navicat for MySQL.app'
end
|
Fix ruby version matcher to check for leading 'ruby-' | require 'rubygems/dependency_installer'
installer = Gem::DependencyInstaller.new
begin
if RUBY_VERSION >= '2.0'
puts "Installing byebug for Ruby #{RUBY_VERSION}"
installer.install 'byebug'
elsif RUBY_VERSION >= '1.9'
puts "Installing debugger for Ruby #{RUBY_VERSION}"
installer.install 'debugger'
elsif RUBY_VERSION >= '1.8'
puts "Installing ruby-debug for Ruby #{RUBY_VERSION}"
installer.install 'ruby-debug'
end
rescue => e
warn "#{$0}: #{e}"
exit!
end
f = File.open(File.join(File.dirname(__FILE__), "Rakefile"), "w") # create dummy rakefile to indicate success
f.write("task :default\n")
f.close
| require 'rubygems/dependency_installer'
installer = Gem::DependencyInstaller.new
begin
ruby_version = RUBY_VERSION.sub /^[a-z-]*/, ''
if ruby_version >= '2.0'
puts "Installing byebug for Ruby #{ruby_version}"
installer.install 'byebug'
elsif ruby_version >= '1.9'
puts "Installing debugger for Ruby #{ruby_version}"
installer.install 'debugger'
elsif ruby_version >= '1.8'
puts "Installing ruby-debug for Ruby #{ruby_version}"
installer.install 'ruby-debug'
end
rescue => e
warn "#{$0}: #{e}"
exit!
end
f = File.open(File.join(File.dirname(__FILE__), "Rakefile"), "w") # create dummy rakefile to indicate success
f.write("task :default\n")
f.close
|
Fix bug if you provided invalid y/n response | class GitCleanup
module Helper
def self.boolean(question)
puts "#{question} (y/n)"
answer = STDIN.gets.chomp
if answer == 'y'
yield
elsif answer == 'n'
return false
else
boolean(question)
end
end
end
end | class GitCleanup
module Helper
def self.boolean(question, &block)
puts "#{question} (y/n)"
answer = STDIN.gets.chomp
if answer == 'y'
yield
elsif answer == 'n'
return false
else
boolean(question, &block)
end
end
end
end |
Add comments explaining the wait | module QA
module Page
module Label
class Index < Page::Base
view 'app/views/projects/labels/index.html.haml' do
element :label_create_new
end
view 'app/views/shared/empty_states/_labels.html.haml' do
element :label_svg
end
def go_to_new_label
wait(reload: false) do
within_element(:label_svg) do
has_css?('.js-lazy-loaded')
end
end
click_element :label_create_new
end
end
end
end
end
| module QA
module Page
module Label
class Index < Page::Base
view 'app/views/projects/labels/index.html.haml' do
element :label_create_new
end
view 'app/views/shared/empty_states/_labels.html.haml' do
element :label_svg
end
def go_to_new_label
# The 'labels.svg' takes a fraction of a second to load after which the "New label" button shifts up a bit
# This can cause webdriver to miss the hit so we wait for the svg to load (implicitly with has_css?)
# before clicking the button.
within_element(:label_svg) do
has_css?('.js-lazy-loaded')
end
click_element :label_create_new
end
end
end
end
end
|
Fix double flash responders on sign on | require "application_responder"
class ApplicationController < ActionController::Base
self.responder = ApplicationResponder
respond_to :html
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
def after_sign_in_path_for(resource)
user_profile_path(resource)
end
end
| require "application_responder"
class ApplicationController < ActionController::Base
self.responder = ActionController::Responder
respond_to :html
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
def after_sign_in_path_for(resource)
user_profile_path(resource)
end
end
|
Set JSON options via customizable default options |
module SearchFlip
module JSON
def self.generate(obj)
Oj.dump(obj, mode: :custom, use_to_json: true)
end
end
end
|
module SearchFlip
class JSON
@default_options = {
mode: :custom,
use_to_json: true
}
def self.default_options
@default_options
end
def self.generate(obj)
Oj.dump(obj, default_options)
end
end
end
|
Use block for multi-assignment protection | namespace :spree_multi_tenant do
desc "Create a new tenant"
task :create_tenant => :environment do
domain = ENV["domain"]
code = ENV["code"]
if domain.blank? or code.blank?
puts "Error: domain and code must be specified"
puts "(e.g. rake spree_multi_tenant:create_tenant domain=mydomain.com code=mydomain)"
exit
end
tenant = Spree::Tenant.create!({:domain => domain.dup, :code => code.dup})
tenant.create_template_and_assets_paths
end
end
| namespace :spree_multi_tenant do
desc "Create a new tenant"
task :create_tenant => :environment do
domain = ENV["domain"]
code = ENV["code"]
if domain.blank? or code.blank?
puts "Error: domain and code must be specified"
puts "(e.g. rake spree_multi_tenant:create_tenant domain=mydomain.com code=mydomain)"
exit
end
tenant = Spree::Tenant.create! do |t|
t.domain = domain.dup
t.code = code.dup
end
tenant.create_template_and_assets_paths
end
end
|
Read box file in binary mode for checksum | # This is an "interface" that should be implemented by any digest class
# passed into FileChecksum. Note that this isn't strictly enforced at
# the moment, and this class isn't directly used. It is merely here for
# documentation of structure of the class.
class DigestClass
def update(string); end
def hexdigest; end
end
class FileChecksum
BUFFER_SIZE = 16328
# Initializes an object to calculate the checksum of a file. The given
# ``digest_klass`` should implement the ``DigestClass`` interface. Note
# that the built-in Ruby digest classes duck type this properly:
# Digest::MD5, Digest::SHA1, etc.
def initialize(path, digest_klass)
@digest_klass = digest_klass
@path = path
end
# This calculates the checksum of the file and returns it as a
# string.
#
# @return [String]
def checksum
digest = @digest_klass.new
File.open(@path, "r") do |f|
while !f.eof
begin
buf = f.readpartial(BUFFER_SIZE)
digest.update(buf)
rescue EOFError
# Although we check for EOF earlier, this seems to happen
# sometimes anyways [GH-2716].
break
end
end
end
return digest.hexdigest
end
end
| # This is an "interface" that should be implemented by any digest class
# passed into FileChecksum. Note that this isn't strictly enforced at
# the moment, and this class isn't directly used. It is merely here for
# documentation of structure of the class.
class DigestClass
def update(string); end
def hexdigest; end
end
class FileChecksum
BUFFER_SIZE = 16328
# Initializes an object to calculate the checksum of a file. The given
# ``digest_klass`` should implement the ``DigestClass`` interface. Note
# that the built-in Ruby digest classes duck type this properly:
# Digest::MD5, Digest::SHA1, etc.
def initialize(path, digest_klass)
@digest_klass = digest_klass
@path = path
end
# This calculates the checksum of the file and returns it as a
# string.
#
# @return [String]
def checksum
digest = @digest_klass.new
File.open(@path, "rb") do |f|
while !f.eof
begin
buf = f.readpartial(BUFFER_SIZE)
digest.update(buf)
rescue EOFError
# Although we check for EOF earlier, this seems to happen
# sometimes anyways [GH-2716].
break
end
end
end
return digest.hexdigest
end
end
|
Remove rdoc comment, as the parser should no longer complain on that line. | # Copyright (c) 2010 Michael Dvorkin
#
# Awesome Print is freely distributable under the terms of MIT license.
# See LICENSE file or http://www.opensource.org/licenses/mit-license.php
#------------------------------------------------------------------------------
class String # :nodoc:
[ :gray, :red, :green, :yellow, :blue, :purple, :cyan, :white ].each_with_index do |color, i|
if STDOUT.tty? && ENV['TERM'] && ENV['TERM'] != 'dumb'
define_method color do "\033[1;#{30+i}m#{self}\033[0m" end
define_method :"#{color}ish" do "\033[0;#{30+i}m#{self}\033[0m" end
else
define_method color do self end
alias_method :"#{color}ish", color # <- This break Rdoc: Name or symbol expected (got #<RubyToken::TkDSTRING
end
end
alias :black :grayish
alias :pale :whiteish
end
| # Copyright (c) 2010 Michael Dvorkin
#
# Awesome Print is freely distributable under the terms of MIT license.
# See LICENSE file or http://www.opensource.org/licenses/mit-license.php
#------------------------------------------------------------------------------
class String # :nodoc:
[ :gray, :red, :green, :yellow, :blue, :purple, :cyan, :white ].each_with_index do |color, i|
if STDOUT.tty? && ENV['TERM'] && ENV['TERM'] != 'dumb'
define_method color do "\033[1;#{30+i}m#{self}\033[0m" end
define_method :"#{color}ish" do "\033[0;#{30+i}m#{self}\033[0m" end
else
define_method color do self end
alias_method :"#{color}ish", color
end
end
alias :black :grayish
alias :pale :whiteish
end
|
Use old hash syntax for old Rubies | module Rollbar
# Report any uncaught errors in a job to Rollbar
module ActiveJob
def self.included(base)
base.send :rescue_from, Exception do |exception|
Rollbar.error(exception, job: self.class.name, job_id: job_id)
end
end
end
end
| module Rollbar
# Report any uncaught errors in a job to Rollbar
module ActiveJob
def self.included(base)
base.send :rescue_from, Exception do |exception|
Rollbar.error(exception, :job => self.class.name, :job_id => job_id)
end
end
end
end
|
Check if image saved and a key exists | require 'spec_helper'
describe Image do
let(:valid_attributes) do
extend ActionDispatch::TestProcess
{ :user_id => 1, :file => fixture_file_upload('chicken_rice.jpg') }
end
it 'will have a key' do
image = Image.create! valid_attributes
image.key should exist
end
end
| require 'spec_helper'
describe Image do
let(:valid_attributes) do
extend ActionDispatch::TestProcess
{ :user_id => 1, :file => fixture_file_upload('chicken_rice.jpg') }
end
it 'will have a key' do
image = Image.create! valid_attributes
Image.all.should have(1).item
Image.first.key.should exist
end
end
|
Update project name in gemspec. | # -*- encoding: utf-8 -*-
require File.expand_path('../lib/gitra/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = 'gitra'
gem.version = "#{Gitra::VERSION}.dev"
gem.summary = "Git Route Analyzer"
gem.description = "Analyze branches and continuity in a git repository."
gem.authors = ['David Lantos']
gem.email = ['david.lantos@gmail.com']
gem.homepage = 'http://github.com/sldblog/gitra'
gem.required_ruby_version = '>= 1.9.3'
gem.add_dependency 'git'
gem.add_dependency 'term-ansicolor'
gem.add_development_dependency 'rake'
gem.add_development_dependency 'minitest'
gem.executables = ['gitra']
gem.files = Dir['Rakefile', '{bin,lib,spec}/**/*', 'README*', 'LICENSE*'] & `git ls-files -z`.split("\0")
gem.test_files = gem.files.grep(%r{^(spec)/})
gem.require_paths = ["lib"]
end
| # -*- encoding: utf-8 -*-
require File.expand_path('../lib/gitra/version', __FILE__)
Gem::Specification.new do |gem|
gem.name = 'gitra'
gem.version = "#{Gitra::VERSION}.dev"
gem.summary = "Git Repository Analyzer"
gem.description = "Analyze branches and continuity in a git repository."
gem.authors = ['David Lantos']
gem.email = ['david.lantos@gmail.com']
gem.homepage = 'http://github.com/sldblog/gitra'
gem.required_ruby_version = '>= 1.9.3'
gem.add_dependency 'git'
gem.add_dependency 'term-ansicolor'
gem.add_development_dependency 'rake'
gem.add_development_dependency 'minitest'
gem.executables = ['gitra']
gem.files = Dir['Rakefile', '{bin,lib,spec}/**/*', 'README*', 'LICENSE*'] & `git ls-files -z`.split("\0")
gem.test_files = gem.files.grep(%r{^(spec)/})
gem.require_paths = ["lib"]
end
|
Use AD::SystemTestCase on Rails 5.2+ | # frozen_string_literal: true
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
# load Rails first
require 'rails'
# load the plugin
require 'active_decorator'
# needs to load the app next
require 'fake_app/fake_app'
require 'test/unit/rails/test_help'
class ActionDispatch::IntegrationTest
include Capybara::DSL
end
module DatabaseDeleter
def setup
Book.delete_all
Author.delete_all
Movie.delete_all
super
end
end
Test::Unit::TestCase.send :prepend, DatabaseDeleter
CreateAllTables.up unless ActiveRecord::Base.connection.table_exists? 'authors'
| # frozen_string_literal: true
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
# load Rails first
require 'rails'
# load the plugin
require 'active_decorator'
Bundler.require
require 'capybara'
require 'selenium/webdriver'
# needs to load the app next
require 'fake_app/fake_app'
require 'test/unit/rails/test_help'
begin
require 'action_dispatch/system_test_case'
rescue LoadError
Capybara.register_driver :chrome do |app|
options = Selenium::WebDriver::Chrome::Options.new(args: %w[no-sandbox headless disable-gpu])
Capybara::Selenium::Driver.new(app, browser: :chrome, options: options)
end
Capybara.javascript_driver = :chrome
class ActionDispatch::IntegrationTest
include Capybara::DSL
end
else
ActionDispatch::SystemTestCase.driven_by(:selenium, using: :headless_chrome)
end
module DatabaseDeleter
def setup
Book.delete_all
Author.delete_all
Movie.delete_all
super
end
end
Test::Unit::TestCase.send :prepend, DatabaseDeleter
CreateAllTables.up unless ActiveRecord::Base.connection.table_exists? 'authors'
|
Fix unit test coveralls to run outside travis | if ENV['TRAVIS']
require 'coveralls'
Coveralls.wear!
end
ENV["RAILS_ENV"] ||= "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActionController::TestCase
include Devise::Test::ControllerHelpers
end
class ActiveSupport::TestCase
fixtures :all
end
# VCR is used to 'record' HTTP interactions with
# third party services used in tests, and play em
# back. Useful for efficiency, also useful for
# testing code against API's that not everyone
# has access to -- the responses can be cached
# and re-used.
require 'vcr'
require 'webmock'
# To allow us to do real HTTP requests in a VCR.turned_off, we
# have to tell webmock to let us.
WebMock.allow_net_connect!
VCR.configure do |c|
c.default_cassette_options = { :record => :once, :allow_playback_repeats => true }
c.cassette_library_dir = 'test/vcr_cassettes'
# webmock needed for HTTPClient testing
c.hook_into :webmock
c.allow_http_connections_when_no_cassette = true
end
| require 'coveralls'
Coveralls.wear_merged!('rails')
ENV["RAILS_ENV"] ||= "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActionController::TestCase
include Devise::Test::ControllerHelpers
end
class ActiveSupport::TestCase
fixtures :all
end
# VCR is used to 'record' HTTP interactions with
# third party services used in tests, and play em
# back. Useful for efficiency, also useful for
# testing code against API's that not everyone
# has access to -- the responses can be cached
# and re-used.
require 'vcr'
require 'webmock'
# To allow us to do real HTTP requests in a VCR.turned_off, we
# have to tell webmock to let us.
WebMock.allow_net_connect!
VCR.configure do |c|
c.default_cassette_options = { :record => :once, :allow_playback_repeats => true }
c.cassette_library_dir = 'test/vcr_cassettes'
# webmock needed for HTTPClient testing
c.hook_into :webmock
c.allow_http_connections_when_no_cassette = true
end
|
Remove unused test helper method. | require 'fewer'
require 'fileutils'
require 'pathname'
require 'test/unit'
require 'rubygems'
require 'leftright'
require 'less'
require 'mocha'
require 'rack/test'
require 'fakefs'
class FakeFS::File
def self.join(*parts)
RealFile.join(parts)
end
end
module TestHelper
private
def decode(encoded)
Fewer::Serializer.decode(fs, encoded)
end
def encode(paths)
Fewer::Serializer.encode(fs, paths)
end
def fs(path = '')
root = File.expand_path('../fs', __FILE__)
FileUtils.mkdir_p(root)
File.join(root, path)
end
def template_root
File.expand_path('../templates', __FILE__)
end
def touch(path)
pathed = fs(path)
FileUtils.touch(pathed)
pathed
end
end
| require 'fewer'
require 'fileutils'
require 'pathname'
require 'test/unit'
require 'rubygems'
require 'leftright'
require 'less'
require 'mocha'
require 'rack/test'
require 'fakefs'
class FakeFS::File
def self.join(*parts)
RealFile.join(parts)
end
end
module TestHelper
private
def decode(encoded)
Fewer::Serializer.decode(fs, encoded)
end
def encode(paths)
Fewer::Serializer.encode(fs, paths)
end
def fs(path = '')
root = File.expand_path('../fs', __FILE__)
FileUtils.mkdir_p(root)
File.join(root, path)
end
def touch(path)
pathed = fs(path)
FileUtils.touch(pathed)
pathed
end
end
|
Initialize PM topics rspec test | require 'rails_helper'
describe 'the private messaging system', type: feature do
before(:each) do
FactoryGirl.create(:ip_cache, ip_address: '1.2.3.4')
end
let(:sender) do
FactoryGirl.create(:activated_user, email: 'sender@example.com')
end
# let(:recipient) do
# FactoryGirl.create(:activated_user, email: 'recipient@example.com')
# end
it 'disallows a user from sending themselves a private message' do
visit '/login'
fill_in 'E-mail', with: 'sender@example.com'
fill_in 'Password', with: 'password'
click_button 'Log In'
expect(current_path).to eq '/'
expect(page).to have_content 'sender@example.com'
click_link 'New Topic'
fill_in 'Title', with: 'Inspiring topic title'
fill_in 'Message', with: 'Bold and motivational message body'
click_button 'Post'
expect(current_path).to eq '/topics/1'
click_link 'Contact'
expect(current_path).to eq '/topics/1'
expect(page).to have_css 'alert'
end
end
| |
Tidy up reordering topic section feature spec helpers | require 'rails_helper'
RSpec.describe 'Re-ordering topic sections', type: :feature, js: true do
before do
stub_any_publishing_api_call
# Ensure that all elements are within the browser 'viewport' when dragging
# things around by making the page really tall
page.driver.resize(1024, 2000)
end
it 'lets you re-order topic sections' do
topic = create(:topic)
topic.topic_sections << create(:topic_section, title: "Section B", topic: topic)
topic.topic_sections << create(:topic_section, title: "Section A", topic: topic)
topic.topic_sections << create(:topic_section, title: "Section C", topic: topic)
visit edit_topic_path(topic)
drag_topic_section_above("Section A", "Section B")
click_button "Save"
expect(sections_in_order).to eq ["Section A", "Section B", "Section C"]
end
private
def drag_topic_section_above(dragged_section_title, destination_section_title)
handle = within_topic_section dragged_section_title do
find('.js-topic-section-handle')
end
destination = within_topic_section destination_section_title do
find('.js-topic-section-handle')
end
handle.drag_to destination
end
def sections_in_order
all('.list-group-item input[placeholder="Heading Title"]').map &:value
end
end
| require 'rails_helper'
RSpec.describe 'Re-ordering topic sections', type: :feature, js: true do
before do
stub_any_publishing_api_call
# Ensure that all elements are within the browser 'viewport' when dragging
# things around by making the page really tall
page.driver.resize(1024, 2000)
end
it 'lets you re-order topic sections' do
topic = create(:topic)
topic.topic_sections << create(:topic_section, title: "Section B", topic: topic)
topic.topic_sections << create(:topic_section, title: "Section A", topic: topic)
topic.topic_sections << create(:topic_section, title: "Section C", topic: topic)
visit edit_topic_path(topic)
drag_topic_section_above("Section A", "Section B")
click_button "Save"
expect(sections_in_order).to eq ["Section A", "Section B", "Section C"]
end
private
def handle_for_topic_section(section_title)
within_topic_section(section_title) { find('.js-topic-section-handle') }
end
def drag_topic_section_above(dragged_section_title, destination_section_title)
handle_for_topic_section(dragged_section_title).drag_to(
handle_for_topic_section(destination_section_title)
)
end
def sections_in_order
all('.list-group-item input[placeholder="Heading Title"]').map &:value
end
end
|
Remove unnecessary `self` return in `Table` RGSSx class. | class Table
attr_reader :xsize
attr_reader :ysize
attr_reader :zsize
def self._load(array) # :nodoc:
self.class.new.instance_eval do
@size, @xsize, @ysize, @zsize, _, *@data = array.unpack('LLLLLS*')
self
end
end
end | class Table
attr_reader :xsize
attr_reader :ysize
attr_reader :zsize
def self._load(array) # :nodoc:
self.class.new.instance_eval do
@size, @xsize, @ysize, @zsize, _, *@data = array.unpack('LLLLLS*')
end
end
end |
Add tests for Instance::Announcement's associations | require 'rails_helper'
RSpec.describe Instance::Announcement, type: :model do
it { is_expected.to validate_presence_of(:title) }
end
| require 'rails_helper'
RSpec.describe Instance::Announcement, type: :model do
it { is_expected.to belong_to(:creator).class_name(User.name) }
it { is_expected.to belong_to(:instance).inverse_of(:announcements) }
it { is_expected.to validate_presence_of(:title) }
end
|
Update the test helper to error on unknown files. | require 'fakeweb'
module IDology
module TestHelper
def fake_idology(request_type, response_name)
FakeWeb.register_uri(:post,
"#{Subject.base_uri}#{Subject::Paths[request_type]}",
:body => idology_response_path(response_name))
end
def idology_response_path(name)
File.dirname(__FILE__)+"/../spec/fixtures/#{name}.xml"
end
def load_idology_response(name)
File.read idology_response_path(name)
end
def parse_idology_response(name)
Response.parse(load_idology_response(name))
end
end
end | require 'fakeweb'
module IDology
module TestHelper
def fake_idology(request_type, response_name)
FakeWeb.register_uri(:post,
"#{Subject.base_uri}#{Subject::Paths[request_type]}",
:body => idology_response_path(response_name))
end
def idology_response_path(name)
file = File.expand_path(File.dirname(__FILE__)+"/../spec/fixtures/#{name}.xml")
raise "Unknown File: #{file}" unless File.exist?(file)
end
def load_idology_response(name)
File.read idology_response_path(name)
end
def parse_idology_response(name)
Response.parse(load_idology_response(name))
end
end
end |
Use lower bundler version in gemspec | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'ivapi/version'
Gem::Specification.new do |gem|
gem.name = 'ivapi'
gem.author = 'Justas Palumickas'
gem.email = 'jpalumickas@gmail.com'
gem.description = %q{ Gem which helps to communicate with http://www.iv.lt API. }
gem.summary = gem.description
gem.homepage = 'https://github.com/jpalumickas/ivapi/'
gem.license = 'MIT'
gem.files = `git ls-files -z`.split("\x0")
gem.executables = gem.files.grep(%r{^bin/}) { |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ['lib']
gem.add_dependency 'addressable', '~> 2.3'
gem.add_dependency 'faraday', '~> 0.9.0'
gem.add_dependency 'faraday_middleware', '~> 0.9.1'
gem.add_dependency 'hashie', '~> 3.3'
gem.add_dependency 'multi_json', '~> 1.10'
gem.add_development_dependency 'bundler', '~> 1.7'
gem.add_development_dependency 'rake', '~> 10.0'
gem.version = Ivapi::VERSION
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'ivapi/version'
Gem::Specification.new do |gem|
gem.name = 'ivapi'
gem.author = 'Justas Palumickas'
gem.email = 'jpalumickas@gmail.com'
gem.description = %q{ Gem which helps to communicate with http://www.iv.lt API. }
gem.summary = gem.description
gem.homepage = 'https://github.com/jpalumickas/ivapi/'
gem.license = 'MIT'
gem.files = `git ls-files -z`.split("\x0")
gem.executables = gem.files.grep(%r{^bin/}) { |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ['lib']
gem.add_dependency 'addressable', '~> 2.3'
gem.add_dependency 'faraday', '~> 0.9.0'
gem.add_dependency 'faraday_middleware', '~> 0.9.1'
gem.add_dependency 'hashie', '~> 3.3'
gem.add_dependency 'multi_json', '~> 1.10'
gem.add_development_dependency 'bundler', '~> 1.5'
gem.add_development_dependency 'rake', '~> 10.0'
gem.version = Ivapi::VERSION
end
|
Switch encryption methods to use gibberish. | module PreciousCargo
# Public: A collection of methods to encrypt and decrypt data using
# a supplied secret.
module Data
class << self
# Public: Encrypt the supplied data using a secret string. Currently only supports AES 256 encryption.
# data - The data to be encrypted.
# options - Hash of values used to encrypt the secret.
# :secret - A secret string.
#
# Returns the AES encrypted data.
def encrypt!(data, options = {})
secret = options.delete(:secret)
cipher = OpenSSL::Cipher::AES.new(256, :CBC)
cipher.encrypt
cipher.key = secret
Base64.encode64(cipher.update(data) + cipher.final)
end
# Public: Decrypt the supplied data using a secret string. Currently only supports AES 256 encryption.
# data - The data to be encrypted.
# options - Hash of values used to encrypt the secret.
# :secret - A secret string.
#
# Returns the AES encrypted data.
def decrypt!(encrypted_data, options = {})
secret = options.delete(:secret)
encrypted_data = Base64.decode64(encrypted_data)
decipher = OpenSSL::Cipher::AES.new(256, :CBC)
decipher.decrypt
decipher.key = secret
decipher.update(encrypted_data) + decipher.final
end
end
end
end | module PreciousCargo
# Public: A collection of methods to encrypt and decrypt data using
# a supplied secret.
module Data
class << self
# Public: Encrypt the supplied data using a secret string. Currently only supports AES 256 encryption.
# data - The data to be encrypted.
# options - Hash of values used to encrypt the secret.
# :secret - A secret string.
#
# Returns the AES encrypted data.
def encrypt!(data, options = {})
secret = options.delete(:secret)
cipher = Gibberish::AES.new(secret)
cipher.encrypt(data)
end
# Public: Decrypt the supplied data using a secret string. Currently only supports AES 256 encryption.
# data - The data to be encrypted.
# options - Hash of values used to encrypt the secret.
# :secret - A secret string.
#
# Returns the AES encrypted data.
def decrypt!(encrypted_data, options = {})
secret = options.delete(:secret)
cipher = Gibberish::AES.new(secret)
cipher.decrypt(encrypted_data).strip
end
end
end
end |
Disable menu button in RetirementController. | class RetirementsController < ApplicationController
layout 'layouts/_unconstrained'
def alternate_locales
[]
end
end
| class RetirementsController < ApplicationController
layout 'layouts/_unconstrained'
def alternate_locales
[]
end
def display_menu_button_in_header?
false
end
end
|
Add integration test for Amazon Linux AMI | require 'integration_helper'
class AmazonLinux2012_09BootstrapTest < IntegrationTest
def user
"ec2-user"
end
def image_id
"ami-1624987f"
end
def prepare_server
# Do nothing as `solo bootstrap` will do everything
end
include Apache2Bootstrap
end
| |
Change route to share application | #module CatarseStripe
#class Engine < ::Rails::Engine
#isolate_namespace CatarseStripe
#end
#end
module ActionDispatch::Routing
class Mapper
def mount_catarse_stripe_at(mount_location)
scope mount_location do
namespace :payment do
get '/stripe/:id/review' => 'stripe#review', :as => 'review_stripe'
post '/stripe/notifications' => 'stripe#ipn', :as => 'ipn_stripe'
match '/stripe/:id/notifications' => 'stripe#notifications', :as => 'notifications_stripe'
match '/stripe/:id/pay' => 'stripe#pay', :as => 'pay_stripe'
match '/stripe/:id/success' => 'stripe#success', :as => 'success_stripe'
match '/stripe/:id/cancel' => 'stripe#cancel', :as => 'cancel_stripe'
match '/stripe/:id/charge' => 'stripe#charge', :as => 'charge_stripe'
end
end
end
end
end
| #module CatarseStripe
#class Engine < ::Rails::Engine
#isolate_namespace CatarseStripe
#end
#end
module ActionDispatch::Routing
class Mapper
def mount_catarse_stripe_at(mount_location)
scope mount_location do
get 'payment/stripe/:id/review' => 'payment/stripe#review', :as => 'review_stripe'
post 'payment/stripe/notifications' => 'payment/stripe#ipn', :as => 'ipn_stripe'
match 'payment/stripe/:id/notifications' => 'payment/stripe#notifications', :as => 'notifications_stripe'
match 'payment/stripe/:id/pay' => 'payment/stripe#pay', :as => 'pay_stripe'
match 'payment/stripe/:id/success' => 'payment/stripe#success', :as => 'success_stripe'
match 'payment/stripe/:id/cancel' => 'paymentstripe#cancel', :as => 'cancel_stripe'
match 'payment/stripe/:id/charge' => 'paymentstripe#charge', :as => 'charge_stripe'
end
end
end
end
|
Update frames command to support /frames/Path/To/Object URL mapping. | module YARD
module Server
module Commands
class FramesCommand < DisplayObjectCommand
include DocServerHelper
def run
main_url = "#{base_path.gsub(/frames$/, '')}#{object_path}"
if path && !path.empty?
page_title = "Object: #{object_path}"
elsif options[:files] && options[:files].size > 0
page_title = "File: #{options[:files].first.sub(/^#{library_path}\/?/, '')}"
main_url = url_for_file(options[:files].first)
elsif !path || path.empty?
page_title = "Documentation for #{library.name} #{library.version ? '(' + library.version + ')' : ''}"
end
options.update(
:page_title => page_title,
:main_url => main_url,
:template => :doc_server,
:type => :frames
)
render
end
end
end
end
end
| module YARD
module Server
module Commands
class FramesCommand < DisplayObjectCommand
include DocServerHelper
def run
main_url = request.path.gsub(/^(.+)?\/frames\/(#{path})$/, '\1/\2')
if path && !path.empty?
page_title = "Object: #{object_path}"
elsif options[:files] && options[:files].size > 0
page_title = "File: #{options[:files].first.sub(/^#{library_path}\/?/, '')}"
main_url = url_for_file(options[:files].first)
elsif !path || path.empty?
page_title = "Documentation for #{library.name} #{library.version ? '(' + library.version + ')' : ''}"
end
options.update(
:page_title => page_title,
:main_url => main_url,
:template => :doc_server,
:type => :frames
)
render
end
end
end
end
end
|
Revert register proc takes keyword arguments | # frozen_string_literal: true
module ActiveModel
# :stopdoc:
module Type
class Registry
def initialize
@registrations = []
end
def register(type_name, klass = nil, **options, &block)
block ||= proc { |_, *args, **kwargs| klass.new(*args, **kwargs) }
registrations << registration_klass.new(type_name, block, **options)
end
def lookup(symbol, *args, **kwargs)
registration = find_registration(symbol, *args, **kwargs)
if registration
registration.call(self, symbol, *args, **kwargs)
else
raise ArgumentError, "Unknown type #{symbol.inspect}"
end
end
private
attr_reader :registrations
def registration_klass
Registration
end
def find_registration(symbol, *args, **kwargs)
registrations.find { |r| r.matches?(symbol, *args, **kwargs) }
end
end
class Registration
# Options must be taken because of https://bugs.ruby-lang.org/issues/10856
def initialize(name, block, **)
@name = name
@block = block
end
def call(_registry, *args, **kwargs)
if kwargs.any? # https://bugs.ruby-lang.org/issues/10856
block.call(*args, **kwargs)
else
block.call(*args)
end
end
def matches?(type_name, *args, **kwargs)
type_name == name
end
private
attr_reader :name, :block
end
end
# :startdoc:
end
| # frozen_string_literal: true
module ActiveModel
# :stopdoc:
module Type
class Registry
def initialize
@registrations = []
end
def register(type_name, klass = nil, **options, &block)
block ||= proc { |_, *args| klass.new(*args) }
registrations << registration_klass.new(type_name, block, **options)
end
def lookup(symbol, *args, **kwargs)
registration = find_registration(symbol, *args, **kwargs)
if registration
registration.call(self, symbol, *args, **kwargs)
else
raise ArgumentError, "Unknown type #{symbol.inspect}"
end
end
private
attr_reader :registrations
def registration_klass
Registration
end
def find_registration(symbol, *args, **kwargs)
registrations.find { |r| r.matches?(symbol, *args, **kwargs) }
end
end
class Registration
# Options must be taken because of https://bugs.ruby-lang.org/issues/10856
def initialize(name, block, **)
@name = name
@block = block
end
def call(_registry, *args, **kwargs)
if kwargs.any? # https://bugs.ruby-lang.org/issues/10856
block.call(*args, **kwargs)
else
block.call(*args)
end
end
def matches?(type_name, *args, **kwargs)
type_name == name
end
private
attr_reader :name, :block
end
end
# :startdoc:
end
|
Remove null: false constraint on the groups table. | class CreateGroups < ActiveRecord::Migration
def change
create_table :groups do |t|
t.string :primary_number, null: false
t.string :street_name, null: false
t.string :street_suffix, null: false
t.string :city_name, null: false
t.string :state_abbreviation, null: false
t.string :zipcode, null: false
t.timestamps null: false
end
end
end
| class CreateGroups < ActiveRecord::Migration
def change
create_table :groups do |t|
t.string :primary_number, null: false
t.string :street_name, null: false
t.string :street_suffix,
t.string :city_name, null: false
t.string :state_abbreviation, null: false
t.string :zipcode, null: false
t.timestamps null: false
end
end
end
|
Add view helper for toggling cookie notifications. | # -*- encoding: utf-8 -*-
module Rack
module Policy
module Helpers
def cookies_accepted?
accepted = !request.env['rack-policy.consent'].nil?
yield if block_given? && accepted
accepted
end
end # Helpers
end # Policy
end # Rack
| |
Add test for missing channel attributes | require 'helper'
class TestChannel < Test::Unit::TestCase
include DropcasterTest
def setup
@options = YAML.load_file(File.join(FIXTURES_DIR, Dropcaster::CHANNEL_YML))
@channel = Dropcaster::Channel.new(FIXTURES_DIR, @options)
end
def test_item_count
assert_equal(1, @channel.items.size)
end
def test_channel
assert_equal(@options[:title], @channel.title)
assert_equal(@options[:url], @channel.url)
assert_equal(@options[:description], @channel.description)
assert_equal(@options[:subtitle], @channel.subtitle)
assert_equal(@options[:language], @channel.language)
assert_equal(@options[:copyright], @channel.copyright)
assert_equal(@options[:author], @channel.author)
owner = @channel.owner
assert_equal(@options[:owner][:name], owner[:name])
assert_equal(@options[:owner][:email], owner[:email])
assert_equal(URI.join(@options[:url], @options[:image_url]).to_s, @channel.image_url)
# TODO :categories: ['Technology', 'Gadgets']
assert_equal(@options[:explicit], @channel.explicit)
end
end
| require 'helper'
class TestChannel < Test::Unit::TestCase
include DropcasterTest
def setup
@options = YAML.load_file(File.join(FIXTURES_DIR, Dropcaster::CHANNEL_YML))
@channel = Dropcaster::Channel.new(FIXTURES_DIR, @options)
end
def test_item_count
assert_equal(1, @channel.items.size)
end
def test_channel
assert_equal(@options[:title], @channel.title)
assert_equal(@options[:url], @channel.url)
assert_equal(@options[:description], @channel.description)
assert_equal(@options[:subtitle], @channel.subtitle)
assert_equal(@options[:language], @channel.language)
assert_equal(@options[:copyright], @channel.copyright)
assert_equal(@options[:author], @channel.author)
owner = @channel.owner
assert_equal(@options[:owner][:name], owner[:name])
assert_equal(@options[:owner][:email], owner[:email])
assert_equal(URI.join(@options[:url], @options[:image_url]).to_s, @channel.image_url)
# TODO :categories: ['Technology', 'Gadgets']
assert_equal(@options[:explicit], @channel.explicit)
end
def test_raise_on_missing_title
assert_raises Dropcaster::MissingAttributeError do
Dropcaster::Channel.new(FIXTURES_DIR, {:url => 'bar', :description => 'foobar'})
end
end
def test_raise_on_missing_url
assert_raises Dropcaster::MissingAttributeError do
Dropcaster::Channel.new(FIXTURES_DIR, {:title => 'foo', :description => 'foobar'})
end
end
def test_raise_on_missing_description
assert_raises Dropcaster::MissingAttributeError do
Dropcaster::Channel.new(FIXTURES_DIR, {:title => 'foo', :url => 'bar'})
end
end
end
|
Change require in spec helper | require 'pry'
require 'inkling'
Dir["./spec/support/**/*.rb"].each {|f| require f }
RSpec.configure do |config|
config.run_all_when_everything_filtered = true
config.filter_run :focus
config.order = 'random'
end | require 'pry'
require 'inkling-rb'
Dir["./spec/support/**/*.rb"].each {|f| require f }
RSpec.configure do |config|
config.run_all_when_everything_filtered = true
config.filter_run :focus
config.order = 'random'
end |
Fix bug in wiki report; had the org in their twice | # Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'rubygems'
require 'yaml'
require_relative 'db_reporter'
class WikiOnDbReporter < DbReporter
def name()
return "Wiki-Enabled Repositories"
end
def describe()
return "This report shows repositories that have their wikis turned on. "
end
def db_columns()
return [ ['repository', 'org/repo'] ]
end
def db_report(org, sync_db)
wikiOn=sync_db.execute("SELECT r.org || '/' || r.name FROM repository r WHERE has_wiki='1' AND r.org=?", [org])
text = ''
wikiOn.each do |row|
text << " <db-reporting type='WikiOnDbReporter'>#{org}/#{row[0]}</db-reporting>\n"
end
return text
end
end
| # Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'rubygems'
require 'yaml'
require_relative 'db_reporter'
class WikiOnDbReporter < DbReporter
def name()
return "Wiki-Enabled Repositories"
end
def describe()
return "This report shows repositories that have their wikis turned on. "
end
def db_columns()
return [ ['repository', 'org/repo'] ]
end
def db_report(org, sync_db)
wikiOn=sync_db.execute("SELECT r.name FROM repository r WHERE has_wiki='1' AND r.org=?", [org])
text = ''
wikiOn.each do |row|
text << " <db-reporting type='WikiOnDbReporter'>#{org}/#{row[0]}</db-reporting>\n"
end
return text
end
end
|
Use store to match fetch nomenclature | # encoding: utf-8
module BSON
# Provides constant values for each to the BSON types and mappings from raw
# bytes back to these types.
#
# @see http://bsonspec.org/#/specification
#
# @since 2.0.0
module Registry
extend self
# A Mapping of all the BSON types to their corresponding Ruby classes.
#
# @since 2.0.0
MAPPINGS = {}
# Get the class for the single byte identifier for the type in the BSON
# specification.
#
# @example Get the type for the byte.
# BSON::Registry.get("\x01")
#
# @return [ Class ] The corresponding Ruby class for the type.
#
# @see http://bsonspec.org/#/specification
#
# @since 2.0.0
def get(byte)
MAPPINGS.fetch(byte)
end
# Register the Ruby type for the corresponding single byte.
#
# @example Register the type.
# BSON::Registry.register("\x01", Float)
#
# @param [ String ] byte The single byte.
# @param [ Class ] The class the byte maps to.
#
# @return [ Class ] The class.
#
# @since 2.0.0
def register(byte, type)
MAPPINGS[byte] = type
type.define_method(:bson_type) { byte }
end
end
end
| # encoding: utf-8
module BSON
# Provides constant values for each to the BSON types and mappings from raw
# bytes back to these types.
#
# @see http://bsonspec.org/#/specification
#
# @since 2.0.0
module Registry
extend self
# A Mapping of all the BSON types to their corresponding Ruby classes.
#
# @since 2.0.0
MAPPINGS = {}
# Get the class for the single byte identifier for the type in the BSON
# specification.
#
# @example Get the type for the byte.
# BSON::Registry.get("\x01")
#
# @return [ Class ] The corresponding Ruby class for the type.
#
# @see http://bsonspec.org/#/specification
#
# @since 2.0.0
def get(byte)
MAPPINGS.fetch(byte)
end
# Register the Ruby type for the corresponding single byte.
#
# @example Register the type.
# BSON::Registry.register("\x01", Float)
#
# @param [ String ] byte The single byte.
# @param [ Class ] The class the byte maps to.
#
# @return [ Class ] The class.
#
# @since 2.0.0
def register(byte, type)
MAPPINGS.store(byte, type)
type.define_method(:bson_type) { byte }
end
end
end
|
Add FactoryGirl to rspec config | # -*- coding: utf-8 -*-
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rspec'
require 'fakeweb'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
# == Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
config.mock_with :rspec
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
#Fakeweb
FakeWeb.allow_net_connect = false
end
| # -*- coding: utf-8 -*-
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rspec'
require 'fakeweb'
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
# == Mock Framework
#
# If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
config.mock_with :rspec
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
# config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
#Fakeweb
FakeWeb.allow_net_connect = false
end
|
Use RSpec >= 1.1.12 so 1.2 can be used as well | require 'pathname'
require 'rubygems'
gem 'rspec', '~>1.1.12'
require 'spec'
require Pathname(__FILE__).dirname.parent.expand_path + 'lib/dm-migrations'
require Pathname(__FILE__).dirname.parent.expand_path + 'lib/migration_runner'
ADAPTERS = []
def load_driver(name, default_uri)
begin
DataMapper.setup(name, default_uri)
DataMapper::Repository.adapters[:default] = DataMapper::Repository.adapters[name]
ADAPTERS << name
true
rescue LoadError => e
warn "Could not load do_#{name}: #{e}"
false
end
end
#ENV['ADAPTER'] ||= 'sqlite3'
load_driver(:sqlite3, 'sqlite3::memory:')
load_driver(:mysql, 'mysql://localhost/dm_core_test')
load_driver(:postgres, 'postgres://postgres@localhost/dm_core_test')
| require 'pathname'
require 'rubygems'
gem 'rspec', '>=1.1.12'
require 'spec'
require Pathname(__FILE__).dirname.parent.expand_path + 'lib/dm-migrations'
require Pathname(__FILE__).dirname.parent.expand_path + 'lib/migration_runner'
ADAPTERS = []
def load_driver(name, default_uri)
begin
DataMapper.setup(name, default_uri)
DataMapper::Repository.adapters[:default] = DataMapper::Repository.adapters[name]
ADAPTERS << name
true
rescue LoadError => e
warn "Could not load do_#{name}: #{e}"
false
end
end
#ENV['ADAPTER'] ||= 'sqlite3'
load_driver(:sqlite3, 'sqlite3::memory:')
load_driver(:mysql, 'mysql://localhost/dm_core_test')
load_driver(:postgres, 'postgres://postgres@localhost/dm_core_test')
|
Revert "Need to pass through a content-type when using upload_image to appease paperclip" | module Spree
module Api
module TestingSupport
module Helpers
def json_response
JSON.parse(response.body)
end
def assert_not_found!
json_response.should == { "error" => "The resource you were looking for could not be found." }
response.status.should == 404
end
def assert_unauthorized!
json_response.should == { "error" => "You are not authorized to perform that action." }
response.status.should == 401
end
def stub_authentication!
controller.stub :check_for_user_or_api_key
Spree::LegacyUser.stub(:find_by).with(hash_including(:spree_api_key)) { current_api_user }
end
# This method can be overriden (with a let block) inside a context
# For instance, if you wanted to have an admin user instead.
def current_api_user
@current_api_user ||= stub_model(Spree::LegacyUser, :email => "spree@example.com")
end
def image(filename)
File.open(Spree::Api::Engine.root + "spec/fixtures" + filename)
end
def upload_image(filename)
fixture_file_upload(image(filename).path, 'image/jpg')
end
end
end
end
end
| module Spree
module Api
module TestingSupport
module Helpers
def json_response
JSON.parse(response.body)
end
def assert_not_found!
json_response.should == { "error" => "The resource you were looking for could not be found." }
response.status.should == 404
end
def assert_unauthorized!
json_response.should == { "error" => "You are not authorized to perform that action." }
response.status.should == 401
end
def stub_authentication!
controller.stub :check_for_user_or_api_key
Spree::LegacyUser.stub(:find_by).with(hash_including(:spree_api_key)) { current_api_user }
end
# This method can be overriden (with a let block) inside a context
# For instance, if you wanted to have an admin user instead.
def current_api_user
@current_api_user ||= stub_model(Spree::LegacyUser, :email => "spree@example.com")
end
def image(filename)
File.open(Spree::Api::Engine.root + "spec/fixtures" + filename)
end
def upload_image(filename)
fixture_file_upload(image(filename).path)
end
end
end
end
end
|
Rename mistakenly named method to show intent | class HtmlVersionsController < PublicFacingController
layout 'detailed-guidance'
before_filter :find_publication
before_filter :find_supporting_page
include CacheControlHelper
include PublicDocumentRoutesHelper
def index
redirect_to publication_attachment_path(@publication.document, @publication.html_version)
end
def show
@document = @publication
@html_version = @publication.html_version
end
private
def find_publication
unless @publication = Publication.published_as(params[:publication_id])
render text: "Not found", status: :not_found
end
end
def find_supporting_page
unless (@publication.html_version)
render text: "Not found", status: :not_found
end
end
def analytics_format
:publication
end
end
| class HtmlVersionsController < PublicFacingController
layout 'detailed-guidance'
before_filter :find_publication
before_filter :find_html_version
include CacheControlHelper
include PublicDocumentRoutesHelper
def index
redirect_to publication_attachment_path(@publication.document, @publication.html_version)
end
def show
@document = @publication
@html_version = @publication.html_version
end
private
def find_publication
unless @publication = Publication.published_as(params[:publication_id])
render text: "Not found", status: :not_found
end
end
def find_html_version
unless (@publication.html_version)
render text: "Not found", status: :not_found
end
end
def analytics_format
:publication
end
end
|
Migrate now obsolete displayed fields, filters and sorts | namespace :'2018_10_03_remove_fc_from_procedure_presentation' do
task run: :environment do
Class.new do
def run
fix_displayed_fields
fix_sort
fix_filters
end
def fix_displayed_fields
ProcedurePresentation.where(%q`displayed_fields @> '[{"table": "france_connect_information"}]'`).each do |procedure_presentation|
procedure_presentation.displayed_fields = procedure_presentation.displayed_fields.reject do |df|
df['table'] == 'france_connect_information'
end
procedure_presentation.save(validate: false)
end
end
def fix_sort
ProcedurePresentation.where(%q`sort @> '{"table": "france_connect_information"}'`).each do |procedure_presentation|
procedure_presentation.sort = {
"order" => "desc",
"table" => "notifications",
"column" => "notifications"
}
procedure_presentation.save(validate: false)
end
end
def fix_filters
ProcedurePresentation.find_by_sql(
<<~SQL
SELECT procedure_presentations.*
FROM procedure_presentations, LATERAL jsonb_each(filters)
WHERE value @> '[{"table": "france_connect_information"}]'
GROUP BY id;
SQL
).each do |procedure_presentation|
procedure_presentation.filters.keys.each do |key|
procedure_presentation.filters[key] = procedure_presentation.filters[key].reject do |filter|
filter['table'] == 'france_connect_information'
end
end
procedure_presentation.save
end
end
end.new.run
end
end
| |
Update progress action to store some notes, and save the edition at the end | class Admin::GuidesController < InheritedResources::Base
before_filter :authenticate_user!
defaults :route_prefix => 'admin'
def index
@drafts = Guide.in_draft
@published = Guide.published
@archive = Guide.archive
@review_requested = Guide.review_requested
end
def show
@guide = resource
@latest_edition = resource.latest_edition
end
def update
update! { admin_guide_url(@guide, :anchor => 'metadata') }
end
def progress
@guide = resource
@latest_edition = resource.latest_edition
case params[:activity]
when 'request review'
current_user.request_review(@latest_edition)
when 'review'
current_user.review(@latest_edition)
when 'okay'
current_user.okay(@latest_edition)
when 'publish'
current_user.publish(@latest_edition)
end
redirect_to admin_guide_path(@guide), :notice => 'Guide updated'
end
end
| class Admin::GuidesController < InheritedResources::Base
# before_filter :authenticate_user!
defaults :route_prefix => 'admin'
def index
@drafts = Guide.in_draft
@published = Guide.published
@archive = Guide.archive
@review_requested = Guide.review_requested
end
def show
@guide = resource
@latest_edition = resource.latest_edition
end
def update
update! { admin_guide_url(@guide, :anchor => 'metadata') }
end
def progress
@guide = resource
@latest_edition = resource.latest_edition
notes = ''
case params[:activity]
when 'request_review'
current_user.request_review(@latest_edition, notes)
when 'review'
current_user.review(@latest_edition, notes)
when 'okay'
current_user.okay(@latest_edition, notes)
when 'publish'
current_user.publish(@latest_edition, notes)
end
@latest_edition.save
redirect_to admin_guide_path(@guide), :notice => 'Guide updated'
end
end
|
Change the root shell to bash | execute "set the root user shell to bash" do
command "dscl . -create /Users/root UserShell /bin/bash"
end
link "/root" do
to "/var/root"
end
| |
Fix `omnibus cache missing` etc | #
# Copyright 2015 Chef Software, 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.
#
chef_server_contents = IO.read(File.expand_path('../chef-server.rb', __FILE__))
self.instance_eval(chef_server_contents)
name "chef-server-fips"
package_name "chef-server-fips-core"
# Use chef's scripts for everything.
resources_path "#{resources_path}/../chef-server"
package_scripts_path "#{package_scripts_path}/../chef-server"
| #
# Copyright 2015 Chef Software, 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.
#
chef_server_path = File.expand_path('../chef-server.rb', __FILE__)
instance_eval(IO.read(chef_server_path), chef_server_path)
name "chef-server-fips"
package_name "chef-server-fips-core"
# Use chef's scripts for everything.
resources_path "#{resources_path}/../chef-server"
package_scripts_path "#{package_scripts_path}/../chef-server"
|
Add failing spec for normalization | # encoding: UTF-8
require 'spec_helper'
module ICU
module Normalization
# http://bugs.icu-project.org/trac/browser/icu/trunk/source/test/cintltst/cnormtst.c
describe "Normalization" do
it "should normalize a string - decomposed" do
ICU::Normalization.normalize("Å", :nfd).unpack("U*").should == [65, 778]
end
it "should normalize a string - composed" do
ICU::Normalization.normalize("Å", :nfc).unpack("U*").should == [197]
end
# TODO: add more normalization tests
end
end # Normalization
end # ICU
| # encoding: UTF-8
require 'spec_helper'
module ICU
module Normalization
# http://bugs.icu-project.org/trac/browser/icu/trunk/source/test/cintltst/cnormtst.c
describe "Normalization" do
it "should normalize a string - decomposed" do
ICU::Normalization.normalize("Å", :nfd).unpack("U*").should == [65, 778]
end
it "should normalize a string - composed" do
ICU::Normalization.normalize("Å", :nfc).unpack("U*").should == [197]
end
it "should normalize accents" do
ICU::Normalization.normalize("âêîôû", :nfc).should == "aeiou"
end
# TODO: add more normalization tests
end
end # Normalization
end # ICU
|
Use '~> 1.6' for treetop version constraint | Gem::Specification.new do |s|
s.name = 'haproxy_log_parser'
s.version = IO.read('VERSION').chomp
s.authors = ['Toby Hsieh']
s.homepage = 'https://github.com/tobyhs/haproxy_log_parser'
s.summary = 'Parser for HAProxy logs in the HTTP log format'
s.description = s.summary
s.license = 'MIT'
s.add_dependency 'treetop'
s.add_development_dependency 'rspec', '~> 3.5.0'
s.files = `git ls-files`.split($/)
s.test_files = s.files.grep(%r{\Aspec/})
end
| Gem::Specification.new do |s|
s.name = 'haproxy_log_parser'
s.version = IO.read('VERSION').chomp
s.authors = ['Toby Hsieh']
s.homepage = 'https://github.com/tobyhs/haproxy_log_parser'
s.summary = 'Parser for HAProxy logs in the HTTP log format'
s.description = s.summary
s.license = 'MIT'
s.add_dependency 'treetop', '~> 1.6'
s.add_development_dependency 'rspec', '~> 3.5.0'
s.files = `git ls-files`.split($/)
s.test_files = s.files.grep(%r{\Aspec/})
end
|
Add Shane da Silva as maintainer | # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "childprocess/version"
Gem::Specification.new do |s|
s.name = "childprocess"
s.version = ChildProcess::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Jari Bakken", "Eric Kessler"]
s.email = ["morrow748@gmail.com"]
s.homepage = "http://github.com/enkessler/childprocess"
s.summary = %q{A simple and reliable solution for controlling external programs running in the background on any Ruby / OS combination.}
s.description = %q{This gem aims at being a simple and reliable solution for controlling external programs running in the background on any Ruby / OS combination.}
s.rubyforge_project = "childprocess"
s.license = 'MIT'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- spec/*`.split("\n")
s.require_paths = ["lib"]
s.add_development_dependency "rspec", "~> 3.0"
s.add_development_dependency "yard", "~> 0.0"
s.add_development_dependency 'rake', '< 12.0'
s.add_development_dependency 'coveralls', '< 1.0'
# Install FFI gem if we're running on Windows
s.extensions = 'ext/mkrf_conf.rb'
end
| # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "childprocess/version"
Gem::Specification.new do |s|
s.name = "childprocess"
s.version = ChildProcess::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Jari Bakken", "Eric Kessler", "Shane da Silva"]
s.email = ["morrow748@gmail.com", "shane@dasilva.io"]
s.homepage = "http://github.com/enkessler/childprocess"
s.summary = %q{A simple and reliable solution for controlling external programs running in the background on any Ruby / OS combination.}
s.description = %q{This gem aims at being a simple and reliable solution for controlling external programs running in the background on any Ruby / OS combination.}
s.rubyforge_project = "childprocess"
s.license = 'MIT'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- spec/*`.split("\n")
s.require_paths = ["lib"]
s.add_development_dependency "rspec", "~> 3.0"
s.add_development_dependency "yard", "~> 0.0"
s.add_development_dependency 'rake', '< 12.0'
s.add_development_dependency 'coveralls', '< 1.0'
# Install FFI gem if we're running on Windows
s.extensions = 'ext/mkrf_conf.rb'
end
|
Add switch to run integration against live data | require 'yaml'
require 'vcr'
require 'helper'
VCR.configure do |c|
c.hook_into :excon
c.cassette_library_dir = 'test/vcr_cassettes'
c.before_record do |interaction|
interaction.ignore! if interaction.response.status.code >= 400
end
nondeterministic_params = %w(Signature Timestamp StartDate CreatedAfter QueryStartDateTime)
matcher = VCR.request_matchers.uri_without_param(*nondeterministic_params)
c.default_cassette_options = {
match_requests_on: [:method, matcher],
record: :new_episodes
}
end
class IntegrationTest < MiniTest::Test
def api_name
self.class.name.match(/(.*)Test/)[1]
end
def clients
accounts = begin
YAML.load_file(File.expand_path('../mws.yml', __FILE__)).shuffle
rescue Errno::ENOENT
warn('Skipping integration tests')
[]
end
accounts.map do |account|
MWS.const_get(api_name).new.configure do |c|
account.each { |k, v| c.send("#{k}=", v) }
end
end
end
def setup
VCR.insert_cassette(api_name)
end
def teardown
VCR.eject_cassette
end
end
| require 'yaml'
require 'vcr'
require 'helper'
VCR.configure do |c|
c.hook_into :excon
c.cassette_library_dir = 'test/vcr_cassettes'
c.before_record do |interaction|
interaction.ignore! if interaction.response.status.code >= 400
end
nondeterministic_params = %w(Signature Timestamp StartDate CreatedAfter QueryStartDateTime)
matcher = VCR.request_matchers.uri_without_param(*nondeterministic_params)
c.default_cassette_options = {
match_requests_on: [:method, matcher],
record: :new_episodes
}
end
class IntegrationTest < MiniTest::Test
def api_name
self.class.name.match(/(.*)Test/)[1]
end
def clients
accounts = begin
YAML.load_file(File.expand_path('../mws.yml', __FILE__)).shuffle
rescue Errno::ENOENT
warn('Skipping integration tests')
[]
end
accounts.map do |account|
MWS.const_get(api_name).new.configure do |c|
account.each { |k, v| c.send("#{k}=", v) }
end
end
end
def setup
ENV['LIVE'] ? VCR.turn_off! : VCR.insert_cassette(api_name)
end
def teardown
VCR.eject_cassette if VCR.turned_on?
end
end
|
Update podspec version to v0.0.3 | Pod::Spec.new do |s|
s.name = "AutoLayoutBuilder"
s.version = "0.0.2"
s.license = "MIT"
s.summary = "Create adaptive layouts with an expressive yet concise syntax."
s.homepage = "https://github.com/marcbaldwin/AutoLayoutBuilder"
s.author = { "marcbaldwin" => "marc.baldwin88@gmail.com" }
s.description = %{
AutoLayoutBuilder is an expressive and concise wrapper for Apple's AutoLayout.
It provides shorthand notation for creating readable, flexible layouts.
}
s.source = { :git => "https://github.com/marcbaldwin/AutoLayoutBuilder.git", :tag => "v0.0.2" }
s.source_files = "AutoLayout"
s.platform = :ios, '8.0'
s.frameworks = "Foundation", "UIKit"
s.requires_arc = true
end
| Pod::Spec.new do |s|
s.name = "AutoLayoutBuilder"
s.version = "0.0.3"
s.license = "MIT"
s.summary = "Create adaptive layouts with an expressive yet concise syntax."
s.homepage = "https://github.com/marcbaldwin/AutoLayoutBuilder"
s.author = { "marcbaldwin" => "marc.baldwin88@gmail.com" }
s.description = %{
AutoLayoutBuilder is an expressive and concise wrapper for Apple's AutoLayout.
It provides shorthand notation for creating readable, flexible layouts.
}
s.source = { :git => "https://github.com/marcbaldwin/AutoLayoutBuilder.git", :tag => "v0.0.3" }
s.source_files = "AutoLayout"
s.platform = :ios, '8.0'
s.frameworks = "Foundation", "UIKit"
s.requires_arc = true
end
|
Remove double quotes from gemspec file | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'neighborly/balanced/bankaccount/version'
Gem::Specification.new do |spec|
spec.name = "neighborly-balanced-bankaccount"
spec.version = Neighborly::Balanced::Bankaccount::VERSION
spec.authors = ['Josemar Luedke', 'Irio Musskopf']
spec.email = %w(josemarluedke@gmail.com iirineu@gmail.com)
spec.summary = 'Neighbor.ly integration with Bank Account Balanced Payments.'
spec.description = 'Neighbor.ly integration with Bank Account Balanced Payments.'
spec.homepage = 'https://github.com/neighborly/neighborly-balanced-bankaccount'
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency 'neighborly-balanced', '~> 0'
spec.add_dependency 'rails'
spec.add_development_dependency 'rspec-rails'
spec.add_development_dependency "sqlite3"
end
| # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'neighborly/balanced/bankaccount/version'
Gem::Specification.new do |spec|
spec.name = 'neighborly-balanced-bankaccount'
spec.version = Neighborly::Balanced::Bankaccount::VERSION
spec.authors = ['Josemar Luedke', 'Irio Musskopf']
spec.email = %w(josemarluedke@gmail.com iirineu@gmail.com)
spec.summary = 'Neighbor.ly integration with Bank Account Balanced Payments.'
spec.description = 'Neighbor.ly integration with Bank Account Balanced Payments.'
spec.homepage = 'https://github.com/neighborly/neighborly-balanced-bankaccount'
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0")
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ['lib']
spec.add_dependency 'neighborly-balanced', '~> 0'
spec.add_dependency 'rails'
spec.add_development_dependency 'rspec-rails'
spec.add_development_dependency 'sqlite3'
end
|
Use delegate instead of writing each by hand. | module Respect
module Rails
# The implementation is strongly inspired from
# ActionDispatch::Routing::RoutesInspector.
class RoutesSet
include Enumerable
def initialize
@engines = {}
@engines["application"] = collect_routes(::Rails.application.routes.routes)
end
attr_reader :engines
def routes
@engines["application"]
end
def each(&block)
routes.each(&block)
end
private
def collect_routes(routes, mounted_point = nil)
result = []
routes.each do |route|
route = RouteWrapper.new(route, mounted_point)
next if route.internal?
if route.engine?
result += collect_engine_routes(route)
else
result << route
end
end
result.sort!
end
def collect_engine_routes(route)
return unless route.engine?
name = route.endpoint
return if @engines[name]
routes = route.rack_app.routes
if routes.is_a?(ActionDispatch::Routing::RouteSet)
@engines[name] = collect_routes(routes.routes, route)
else
[]
end
end
end # class RoutesSet
end # module Rails
end # module Respect
| module Respect
module Rails
# The implementation is strongly inspired from
# ActionDispatch::Routing::RoutesInspector.
class RoutesSet
include Enumerable
def initialize
@engines = {}
@engines["application"] = collect_routes(::Rails.application.routes.routes)
end
attr_reader :engines
def routes
@engines["application"]
end
delegate :each, to: :routes
private
def collect_routes(routes, mounted_point = nil)
result = []
routes.each do |route|
route = RouteWrapper.new(route, mounted_point)
next if route.internal?
if route.engine?
result += collect_engine_routes(route)
else
result << route
end
end
result.sort!
end
def collect_engine_routes(route)
return unless route.engine?
name = route.endpoint
return if @engines[name]
routes = route.rack_app.routes
if routes.is_a?(ActionDispatch::Routing::RouteSet)
@engines[name] = collect_routes(routes.routes, route)
else
[]
end
end
end # class RoutesSet
end # module Rails
end # module Respect
|
Improve cask for AppCode EAP | cask :v1 => 'appcode-eap' do
version '3.2.0'
sha256 'fa78dc8e2a7430e7173cecec7b6e369f3d2cf442facd7ee0df46592788b00715'
url 'http://download.jetbrains.com/objc/AppCode-141.1689.23.dmg'
homepage 'http://confluence.jetbrains.com/display/OBJC/AppCode+EAP'
license :commercial
app 'AppCode EAP.app'
end
| cask :v1 => 'appcode-eap' do
version '141.1399.2'
sha256 '2dd8a0a9246067ae6e092b9934cbadac6730a74fe400c8929b09792a0c0cda83'
url "https://download.jetbrains.com/objc/AppCode-#{version}.dmg"
name 'AppCode'
homepage 'https://confluence.jetbrains.com/display/OBJC/AppCode+EAP'
license :commercial
app 'AppCode EAP.app'
zap :delete => [
'~/Library/Preferences/com.jetbrains.AppCode-EAP.plist',
'~/Library/Preferences/AppCode32',
'~/Library/Application Support/AppCode32',
'~/Library/Caches/AppCode32',
'~/Library/Logs/AppCode32',
]
conflicts_with :cask => 'appcode-eap-bundled-jdk'
caveats <<-EOS.undent
#{token} requires Java 6 like any other IntelliJ-based IDE.
You can install it with
brew cask install caskroom/homebrew-versions/java6
The vendor (JetBrains) doesn't support newer versions of Java (yet)
due to several critical issues, see details at
https://intellij-support.jetbrains.com/entries/27854363
EOS
end
|
Add caching and a few elements to items | object @item => :items
attributes :id, :guid, :title, :description, :content, :link
node(:href) { |i| item_url(i) }
child :assets do
attributes :id, :mime, :url
end
| cache @item
object @item => :items
attributes :id, :guid, :title, :description, :content, :link
node(:href) { |i| item_url(i) }
node(:excerpt) { |i| i.to_s }
node(:links) { |i| i.links.map(&:url) }
child :assets do
attributes :id, :mime, :url
end
|
Change the parent categories for EA subcategories. | category_map = {
'flooding-and-coastal-change' => ['environment-countryside/flooding-extreme-weather', 'Flooding and extreme weather'],
'wildlife-and-habitat-conservation' => ['environment-countryside/wildlife-biodiversity', 'Wildlife and biodiversity']
}
category_map.each do |subcategory_slug, (new_parent_tag, new_parent_title)|
if subcategory = MainstreamCategory.find_by_slug(subcategory_slug)
subcategory.update_attributes(
parent_tag: new_parent_tag,
parent_title: new_parent_title
)
else
raise "Missing MainstreamCategory #{subcategory_slug}"
end
end
| |
Add enough stubs to instruments spec | require 'spec_helper'
describe Travis::Addons::Email::Instruments::EventHandler do
include Travis::Testing::Stubs
let(:build) { stub_build(state: :failed) }
let(:subject) { Travis::Addons::Email::EventHandler }
let(:publisher) { Travis::Notification::Publisher::Memory.new }
let(:event) { publisher.events[1] }
before :each do
Travis::Notification.publishers.replace([publisher])
subject.any_instance.stubs(:handle)
subject.notify('build:finished', build)
end
it 'publishes a event' do
event.should publish_instrumentation_event(
event: 'travis.addons.email.event_handler.notify:completed',
message: 'Travis::Addons::Email::EventHandler#notify:completed (build:finished) for #<Build id=1>',
)
event[:data].except(:payload).should == {
repository: 'svenfuchs/minimal',
request_id: 1,
object_id: 1,
object_type: 'Build',
event: 'build:finished',
recipients: ['svenfuchs@artweb-design.de'],
}
event[:data][:payload].should_not be_nil
end
end
| require 'spec_helper'
describe Travis::Addons::Email::Instruments::EventHandler do
include Travis::Testing::Stubs
let(:build) { stub_build(state: :failed, repository: repository, on_default_branch?: true) }
let(:subject) { Travis::Addons::Email::EventHandler }
let(:publisher) { Travis::Notification::Publisher::Memory.new }
let(:event) { publisher.events[1] }
let(:repository) {
stub_repo(users: [stub_user(email: 'svenfuchs@artweb-design.de')])
}
before :each do
Travis::Notification.publishers.replace([publisher])
subject.any_instance.stubs(:handle)
subject.notify('build:finished', build)
end
it 'publishes a event' do
event.should publish_instrumentation_event(
event: 'travis.addons.email.event_handler.notify:completed',
message: 'Travis::Addons::Email::EventHandler#notify:completed (build:finished) for #<Build id=1>',
)
event[:data].except(:payload).should == {
repository: 'svenfuchs/minimal',
request_id: 1,
object_id: 1,
object_type: 'Build',
event: 'build:finished',
recipients: ['svenfuchs@artweb-design.de'],
}
event[:data][:payload].should_not be_nil
end
end
|
Remove trailing whitespace before comma | module Browserlog
class LogsController < ApplicationController
before_filter :check_env
before_filter :check_auth
layout 'browserlog/application'
def index
@filename = "#{params[:env]}.log"
@filepath = Rails.root.join("log/#{@filename}")
end
def changes
lines, last_line_number = reader.read(offset: params[:currentLine].to_i)
respond_to do |format|
format.json do
render json: {
lines: lines.map! { |line| colorizer.colorize_line(line) } ,
last_line_number: last_line_number
}
end
end
end
private
def reader
Browserlog::LogReader.new
end
def colorizer
Browserlog::LogColorize.new
end
def check_env
fail unless %w(test development staging production).include?(params[:env])
end
def check_auth
fail 'Logs not allowed on production environment.' if Rails.env.production? && !Browserlog.config.allow_production_logs
end
end
end
| module Browserlog
class LogsController < ApplicationController
before_filter :check_env
before_filter :check_auth
layout 'browserlog/application'
def index
@filename = "#{params[:env]}.log"
@filepath = Rails.root.join("log/#{@filename}")
end
def changes
lines, last_line_number = reader.read(offset: params[:currentLine].to_i)
respond_to do |format|
format.json do
render json: {
lines: lines.map! { |line| colorizer.colorize_line(line) },
last_line_number: last_line_number
}
end
end
end
private
def reader
Browserlog::LogReader.new
end
def colorizer
Browserlog::LogColorize.new
end
def check_env
fail unless %w(test development staging production).include?(params[:env])
end
def check_auth
fail 'Logs not allowed on production environment.' if Rails.env.production? && !Browserlog.config.allow_production_logs
end
end
end
|
Print id by default as commit description | #!/usr/bin/env ruby
story_path = '/tmp/current_pivo.id'
commit_msg_file_path = ARGV[0]
if File.exists?(story_path)
story_id = File.read(story_path).strip
if story_id =~ /(\d{7,})/
commit_msg = IO.read(commit_msg_file_path)
unless commit_msg.include?($1) or commit_msg =~ /Merge branch/
File.open(commit_msg_file_path, 'w') do |file|
file.print story_id
file.print commit_msg
end
end
end
end
| #!/usr/bin/env ruby
story_path = '/tmp/current_pivo.id'
commit_msg_file_path = ARGV[0]
if File.exists?(story_path)
story_id = File.read(story_path).strip
if story_id =~ /(\d{7,})/
commit_msg = IO.read(commit_msg_file_path)
unless commit_msg.include?($1) or commit_msg =~ /Merge branch/
File.open(commit_msg_file_path, 'w') do |file|
file.print "\n" + story_id
file.print commit_msg
end
end
end
end
|
Package version is incremented from patch number 0.1.2 to 0.1.3 | # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'telemetry-logger'
s.version = '0.1.2'
s.summary = 'Logging to STDERR with coloring and levels of severity'
s.description = ' '
s.authors = ['Obsidian Software, Inc']
s.email = 'opensource@obsidianexchange.com'
s.homepage = 'https://github.com/obsidian-btc/error_data'
s.licenses = ['MIT']
s.require_paths = ['lib']
s.files = Dir.glob('{lib}/**/*')
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.2.3'
s.add_runtime_dependency 'clock', '~> 0'
s.add_runtime_dependency 'dependency', '~> 0'
s.add_runtime_dependency 'rainbow', '~> 0'
end
| # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'telemetry-logger'
s.version = '0.1.3'
s.summary = 'Logging to STDERR with coloring and levels of severity'
s.description = ' '
s.authors = ['Obsidian Software, Inc']
s.email = 'opensource@obsidianexchange.com'
s.homepage = 'https://github.com/obsidian-btc/error_data'
s.licenses = ['MIT']
s.require_paths = ['lib']
s.files = Dir.glob('{lib}/**/*')
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.2.3'
s.add_runtime_dependency 'clock', '~> 0'
s.add_runtime_dependency 'dependency', '~> 0'
s.add_runtime_dependency 'rainbow', '~> 1'
end
|
Add new bz_query_entries migation file. | class CreateBzQueryEntries < ActiveRecord::Migration
def change
create_table :bz_query_entries do |t|
t.references :bz_query_output
t.string :bz_id
t.string :verion
t.string :pm_ack
t.string :devel_ack
t.string :qa_ack
t.string :doc_ack
t.string :status
t.timestamps
end
add_index :bz_query_entries, :bz_query_output_id
end
end
| |
Test edgecase where an empty result is returned for FirstLetters | require 'spec_helper'
require_relative '../lib/abcing/first_letters'
describe ABCing::FirstLetters do
it 'collects 2 letters' do
matcher = ABCing::FirstLetters.new ['Bar', 'Foo']
expect(matcher.letters).to eq(['B', 'F'])
end
it 'Only collects unique letters' do
matcher = ABCing::FirstLetters.new(['Zoo', 'Zebra'])
expect(matcher.letters).to eq(['Z'])
end
it 'Orders letter results alphabetically' do
matcher = ABCing::FirstLetters.new(['Cobra', 'Acid', 'Bee'])
expect(matcher.letters).to eq(['A', 'B', 'C'])
end
end
| require 'spec_helper'
require_relative '../lib/abcing/first_letters'
describe ABCing::FirstLetters do
it 'collects 2 letters' do
matcher = ABCing::FirstLetters.new ['Bar', 'Foo']
expect(matcher.letters).to eq(['B', 'F'])
end
it 'Only collects unique letters' do
matcher = ABCing::FirstLetters.new(['Zoo', 'Zebra'])
expect(matcher.letters).to eq(['Z'])
end
it 'Orders letter results alphabetically' do
matcher = ABCing::FirstLetters.new(['Cobra', 'Acid', 'Bee'])
expect(matcher.letters).to eq(['A', 'B', 'C'])
end
it 'Returns an empty result' do
matcher = ABCing::FirstLetters.new([])
expect(matcher.letters).to eq([])
end
end
|
Add example script for importing customers | # frozen_string_literal: true
# Read customer entries in CSV format from STDIN and create those records in
# the database. Example:
#
# rails runner script/import-customers.rb 3359 < FND-customers-Emails.csv
#
# This script was written for a once-off import. If we want to perform this
# task more often, we can make it more flexible and eventually add a
# feature to the user interface.
require 'csv'
enterprise_id = ARGV.first
def check_enterprise_exists(id)
enterprise = Enterprise.find(id)
puts "Importing customers for #{enterprise.name}:"
end
def import_customer(row, enterprise_id)
email = row["Email"].downcase
tag = row["Tag"]
print email
customer = find_or_create_customer(email, enterprise_id)
add_tag(customer, tag)
puts ""
end
def find_or_create_customer(email, enterprise_id)
Customer.find_or_create_by(
email: email,
enterprise_id: enterprise_id,
) { print " - newly imported" }
print " - user exists" if Spree::User.where(email: email).exists?
end
def add_tag(customer, tag)
return if tag.blank?
customer.tag_list.add(tag)
customer.save!
end
check_enterprise_exists(enterprise_id)
CSV($stdin, headers: true, row_sep: "\r\n") do |csv|
csv.each do |row|
import_customer(row, enterprise_id)
end
end
| |
Add commented out test exposing a division parsing bug | require 'spec_helper'
# Specs in this file have access to a helper object that includes
# the DivisionsHelper. For example:
#
# describe DivisionsHelper do
# describe "string concat" do
# it "concats two strings with spaces" do
# expect(helper.concat_strings("this","that")).to eq("this that")
# end
# end
# end
describe DivisionsHelper do
pending "add some examples to (or delete) #{__FILE__}"
end
| require 'spec_helper'
describe DivisionsHelper do
# TODO Enable this test
# describe '#formatted_motion_text' do
# subject { formatted_motion_text division }
# let(:division) { mock_model(Division, motion: "A bill [No. 2] and votes") }
# it { should eq("\n<p>A bill [No. 2] and votes</p>") }
# end
end
|
Add some relations to Composition for players | class Composition < ApplicationRecord
belongs_to :map
belongs_to :user
validates :map, presence: true
end
| class Composition < ApplicationRecord
belongs_to :map
belongs_to :user
has_many :player_selections
has_many :player_heroes, through: :player_selections
has_many :players, through: :player_heroes
has_many :heroes, through: :player_heroes
validates :map, presence: true
end
|
Package version is increased from 0.3.0 to 0.3.1 | # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'casing'
s.version = '0.3.0'
s.summary = 'Convert the case of strings, symbols, and hash keys, including camelCase, PascalCase, and underscore_case'
s.description = ' '
s.authors = ['Obsidian Software, Inc']
s.email = 'opensource@obsidianexchange.com'
s.homepage = 'https://github.com/obsidian-btc/casing'
s.licenses = ['MIT']
s.require_paths = ['lib']
s.files = Dir.glob('{lib}/**/*')
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.2.3'
s.add_development_dependency 'minitest'
s.add_development_dependency 'minitest-spec-context'
s.add_development_dependency 'pry'
s.add_development_dependency 'runner'
end
| # -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = 'casing'
s.version = '0.3.1'
s.summary = 'Convert the case of strings, symbols, and hash keys, including camelCase, PascalCase, and underscore_case'
s.description = ' '
s.authors = ['Obsidian Software, Inc']
s.email = 'opensource@obsidianexchange.com'
s.homepage = 'https://github.com/obsidian-btc/casing'
s.licenses = ['MIT']
s.require_paths = ['lib']
s.files = Dir.glob('{lib}/**/*')
s.platform = Gem::Platform::RUBY
s.required_ruby_version = '>= 2.2.3'
s.add_development_dependency 'minitest'
s.add_development_dependency 'minitest-spec-context'
s.add_development_dependency 'pry'
s.add_development_dependency 'runner'
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.