hexsha
stringlengths 40
40
| size
int64 2
1.01M
| content
stringlengths 2
1.01M
| avg_line_length
float64 1.5
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
1
|
---|---|---|---|---|---|
7a5218942465b0c9f82d0188842024976719b4c3 | 885 | # frozen_string_literal: true
class HeyDoctor::CheckSidekiqHealthService
class << self
SUCCESS = {
success: true,
message: 'Sidekiq is connected'
}.freeze
ERROR = {
success: false,
message: 'Error connecting to sidekiq'
}.freeze
NO_EXECUTOR = {
success: false,
message: 'None sidekiq host was found, add it to the ENV SIDEKIQ_HOSTS' \
' listing your machine(s) ip or dns using ; for each host'
}.freeze
def call
return NO_EXECUTOR if hosts.blank?
hosts.map { |host| response(host).merge({ host: host }) }
end
private
def hosts
@hosts ||= ENV['SIDEKIQ_HOSTS']&.split(';')
end
def response(host)
connected?(host) ? SUCCESS : ERROR
end
def connected?(host)
system("ping -c1 #{host}")
rescue StandardError
false
end
end
end
| 20.113636 | 79 | 0.6 |
e9635cd091b88d3b1b8d21feb1151d48bc11e0ec | 1,019 | begin
require_relative "lib/net/smtp/version"
rescue LoadError # Fallback to load version file in ruby core repository
require_relative "version"
end
Gem::Specification.new do |spec|
spec.name = "net-smtp"
spec.version = Net::SMTP::VERSION
spec.authors = ["Yukihiro Matsumoto"]
spec.email = ["[email protected]"]
spec.summary = %q{Simple Mail Transfer Protocol client library for Ruby.}
spec.description = %q{Simple Mail Transfer Protocol client library for Ruby.}
spec.homepage = "https://github.com/ruby/net-smtp"
spec.license = "BSD-2-Clause"
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = spec.homepage
spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
end
| 36.392857 | 85 | 0.656526 |
39dc9f2066a8384251edc9a762680fd20461d00f | 1,130 | ActiveRecord::Schema.define do
create_table "companies", :force => true do |t|
t.string :name, :null => false
t.date :founded_on
end
create_table "orchards", :force => true do |t|
t.references :company
t.float :acres
t.string :name, :null => false
t.string :location
t.date :planted_on, :null => false
t.integer :revenue
end
create_table "picking_robots", :force => true do |t|
t.references :orchard
t.date :last_serviced
t.string :model
end
create_table "orchards_picking_robots", :force => true, :id => false do |t|
t.references :orchard
t.references :picking_robot
end
create_table "species", :force => true do |t|
t.string :scientific_name, :null => false
t.string :common_name
end
create_table "stands", :force => true do |t|
t.references :orchard
t.string :address, :null => false
end
create_table "trees", :force => true do |t|
t.references :orchard
t.references :species
t.integer :grid_number, :null => false
t.integer :health_rating
t.integer :produce_rating
t.date :planted_on
end
end
| 24.565217 | 77 | 0.652212 |
bb4b09cc6bc750ded72082ab591b49a831caeb32 | 269 | class CreateTags < ActiveRecord::Migration
def change
create_table :tags do |t|
t.string :name, null: false, default: 'latest'
t.integer :repository_id, null: false
t.timestamps null: false
end
add_index :tags, :repository_id
end
end
| 22.416667 | 52 | 0.67658 |
d5790c1df8628bcb2b94dd272e6b19b30713bc29 | 163 | require File.expand_path(File.join(File.dirname(__FILE__), 'ext', 'sunspot'))
require File.expand_path(File.join(File.dirname(__FILE__), 'ext', 'event-calendar'))
| 54.333333 | 84 | 0.760736 |
33a46c1d9286e31d7fb88126acf0609149148fcf | 2,455 | require 'spec_helper'
require 'zlib'
require 'benchmark'
describe Zopfli do
before :all do
@out_dir = File.expand_path(File.join(File.dirname(__FILE__), "../tmp/"))
Dir.mkdir(@out_dir) unless File.exists?(@out_dir)
end
after :all do
@out_dir = File.expand_path(File.join(File.dirname(__FILE__), "../tmp/"))
Dir["#{@out_dir}/*{.txt,.zfl}"].each do |file|
File.delete(file) rescue nil
end
end
it "calculate plus 100 by test_c (verify C)" do
expect(Zopfli::C.test_c(100)).to eq(200)
expect(Zopfli::C.test_c(150)).to eq(250)
end
describe 'check files compression' do
['test0.txt', 'test1.txt', 'test2.svg'].each do |fixture|
it "#{fixture} in result must be the same" do
uncompressed_file = "spec/fixtures/#{fixture}"
compressed_file = "#{@out_dir}/#{fixture}.zfl"
# made compress
Zopfli.compress(uncompressed_file, compressed_file)
uncompressed_data, compressed_data = File.read(uncompressed_file), File.read(compressed_file)
# check
expect(Zlib::Inflate.inflate(compressed_data)).to eq(uncompressed_data)
end
end
end
describe 'check formats' do
[:deflate, :gzip, :zlib].each do |format|
it "#{format} in result must be the same" do
uncompressed_file = "spec/fixtures/test0.txt"
compressed_file = "#{@out_dir}/test0.txt.zfl"
# made compress
Zopfli.compress(uncompressed_file, compressed_file, format)
uncompressed_data, compressed_data = File.read(uncompressed_file), File.read(compressed_file)
# check
case format
when :deflate
# no matchers
when :gzip
gz = Zlib::GzipReader.new(StringIO.new(compressed_data))
expect(gz.read).to eq(uncompressed_data)
else
expect(Zlib::Inflate.inflate(compressed_data)).to eq(uncompressed_data)
end
end
end
end
describe 'check iterations' do
it "with more iterations must be slower" do
uncompressed_file = "spec/fixtures/test0.txt"
compressed_file = "#{@out_dir}/test0.txt.zfl"
# made compress
slow_time = Benchmark.realtime do
Zopfli.compress(uncompressed_file, compressed_file, :zlib, 50)
end
fast_time = Benchmark.realtime do
Zopfli.compress(uncompressed_file, compressed_file, :zlib, 2)
end
expect(fast_time).to be < slow_time
end
end
end | 30.308642 | 101 | 0.64888 |
03c41546f163c4e904b8063f74f387ce8366a80d | 1,050 | require 'application_system_test_case'
class FoodsTest < ApplicationSystemTestCase
setup do
@food = foods(:one)
end
test 'visiting the index' do
visit foods_url
assert_selector 'h1', text: 'Foods'
end
test 'should create food' do
visit foods_url
click_on 'New food'
fill_in 'Measurement unit', with: @food.measurement_unit
fill_in 'Name', with: @food.name
fill_in 'Price', with: @food.price
click_on 'Create Food'
assert_text 'Food was successfully created'
click_on 'Back'
end
test 'should update Food' do
visit food_url(@food)
click_on 'Edit this food', match: :first
fill_in 'Measurement unit', with: @food.measurement_unit
fill_in 'Name', with: @food.name
fill_in 'Price', with: @food.price
click_on 'Update Food'
assert_text 'Food was successfully updated'
click_on 'Back'
end
test 'should destroy Food' do
visit food_url(@food)
click_on 'Destroy this food', match: :first
assert_text 'Food was successfully destroyed'
end
end
| 22.826087 | 60 | 0.692381 |
4a8f35bb6a3b2daf1f06fe2918be2b818b4bc1b4 | 34,278 | require 'rails_helper'
describe 'EPP Contact', epp: true do
before :all do
@xsd = Nokogiri::XML::Schema(File.read('lib/schemas/contact-eis-1.0.xsd'))
Fabricate(:zonefile_setting, origin: 'ee')
Fabricate(:zonefile_setting, origin: 'pri.ee')
Fabricate(:zonefile_setting, origin: 'med.ee')
Fabricate(:zonefile_setting, origin: 'fie.ee')
Fabricate(:zonefile_setting, origin: 'com.ee')
@registrar1 = Fabricate(:registrar1)
@registrar2 = Fabricate(:registrar2)
@epp_xml = EppXml::Contact.new(cl_trid: 'ABC-12345')
Fabricate(:api_user, username: 'registrar1', registrar: @registrar1)
Fabricate(:api_user, username: 'registrar2', registrar: @registrar2)
login_as :registrar1
@contact = Fabricate(:contact, registrar: @registrar1)
@extension = {
ident: {
value: '37605030299',
attrs: { type: 'priv', cc: 'EE' }
},
legalDocument: {
value: 'dGVzdCBmYWlsCg==',
attrs: { type: 'pdf' }
}
}
@update_extension = {
legalDocument: {
value: 'dGVzdCBmYWlsCg==',
attrs: { type: 'pdf' }
}
}
end
context 'with valid user' do
context 'create command' do
def create_request(overwrites = {}, extension = {}, options = {})
extension = @extension if extension.blank?
defaults = {
id: nil,
postalInfo: {
name: { value: 'John Doe' },
org: nil,
addr: {
street: { value: '123 Example' },
city: { value: 'Tallinn' },
pc: { value: '123456' },
cc: { value: 'EE' }
}
},
voice: { value: '+372.1234567' },
fax: nil,
email: { value: '[email protected]' },
authInfo: nil
}
create_xml = @epp_xml.create(defaults.deep_merge(overwrites), extension)
epp_plain_request(create_xml, options)
end
it 'fails if request xml is missing' do
response = epp_plain_request(@epp_xml.create)
response[:results][0][:msg].should ==
"Element '{https://epp.tld.ee/schema/contact-eis-1.0.xsd}create': Missing child element(s). "\
"Expected is one of ( {https://epp.tld.ee/schema/contact-eis-1.0.xsd}id, "\
"{https://epp.tld.ee/schema/contact-eis-1.0.xsd}postalInfo )."
response[:results][0][:result_code].should == '2001'
end
it 'successfully creates a contact' do
response = create_request
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
@contact = Contact.last
@contact.registrar.should == @registrar1
@registrar1.api_users.should include(@contact.creator)
@contact.ident.should == '37605030299'
@contact.street.should == '123 Example'
@contact.legal_documents.count.should == 1
@contact.auth_info.length.should > 0
log = ApiLog::EppLog.last
log.request_command.should == 'create'
log.request_object.should == 'contact'
log.request_successful.should == true
log.api_user_name.should == 'registrar1'
log.api_user_registrar.should == 'registrar1'
end
it 'creates a contact with custom auth info' do
response = create_request({
authInfo: { pw: { value: 'custompw' } }
})
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
@contact = Contact.last
@contact.auth_info.should == 'custompw'
end
it 'successfully saves ident type with legal document' do
extension = {
ident: {
value: '1990-22-12',
attrs: { type: 'birthday', cc: 'US' }
},
legalDocument: {
value: 'dGVzdCBmYWlsCg==',
attrs: { type: 'pdf' }
}
}
response = create_request({}, extension)
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
@contact = Contact.last
@contact.ident_type.should == 'birthday'
@contact.legal_documents.size.should == 1
end
it 'successfully adds registrar' do
response = create_request
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
Contact.last.registrar.should == @registrar1
end
it 'returns result data upon success' do
response = create_request
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
id = response[:parsed].css('resData creData id').first
cr_date = response[:parsed].css('resData creData crDate').first
id.text.length.should == 15
# 5 seconds for what-ever weird lag reasons might happen
cr_date.text.in_time_zone.utc.should be_within(5).of(Time.zone.now)
end
it 'should return email issue' do
response = create_request(email: { value: 'not@valid' })
response[:msg].should == 'Email is invalid [email]'
response[:result_code].should == '2005'
end
it 'should add registrar prefix for code when missing' do
response = create_request({ id: { value: 'abc12345' } })
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
Contact.last.code.should == 'FIRST0:ABC12345'
end
it 'should add registrar prefix for code when missing' do
response = create_request({ id: { value: 'abc:ABC:12345' } })
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
Contact.last.code.should == 'FIRST0:ABC:ABC:12345'
end
it 'should not allow spaces in custom code' do
response = create_request({ id: { value: 'abc 123' } })
response[:msg].should == 'is invalid [code]'
response[:result_code].should == '2005'
end
it 'should not strange characters in custom code' do
response = create_request({ id: { value: '33&$@@' } })
response[:msg].should == 'is invalid [code]'
response[:result_code].should == '2005'
end
it 'should not strange characters in custom code' do
long_str = 'a' * 1000
response = create_request({ id: { value: long_str } })
response[:msg].should == 'Contact code is too long, max 100 characters [code]'
response[:result_code].should == '2005'
end
it 'should not saves ident type with wrong country code' do
extension = {
ident: {
value: '1990-22-12',
attrs: { type: 'birthday', cc: 'WRONG' }
}
}
response = create_request({}, extension)
response[:msg].should == "Element '{https://epp.tld.ee/schema/eis-1.0.xsd}ident', "\
"attribute 'cc': [facet 'maxLength'] The value 'WRONG' has a length of '5'; this exceeds "\
"the allowed maximum length of '2'."
response[:result_code].should == '2001'
end
it 'should return country missing' do
extension = {
ident: {
value: '1990-22-12',
attrs: { type: 'birthday' }
}
}
response = create_request({}, extension)
response[:msg].should == "Element '{https://epp.tld.ee/schema/eis-1.0.xsd}ident': The attribute "\
"'cc' is required but missing."
response[:result_code].should == '2001'
end
it 'should return country missing' do
extension = {
ident: {
value: '1990-22-12'
}
}
response = create_request({}, extension)
response[:msg].should == "Element '{https://epp.tld.ee/schema/eis-1.0.xsd}ident': The attribute "\
"'type' is required but missing."
response[:result_code].should == '2001'
end
it 'should add registrar prefix for code when legacy prefix present' do
response = create_request({ id: { value: 'CID:FIRST0:abc:ABC:NEW:12345' } })
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
Contact.last.code.should == 'FIRST0:CID:FIRST0:ABC:ABC:NEW:12345'
end
it 'should not remove suffix CID' do
response = create_request({ id: { value: 'CID:FIRST0:abc:CID:ABC:NEW:12345' } })
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
Contact.last.code.should == 'FIRST0:CID:FIRST0:ABC:CID:ABC:NEW:12345'
end
it 'should not add registrar prefix for code when prefix present' do
response = create_request({ id: { value: 'FIRST0:abc22' } })
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
Contact.last.code.should == 'FIRST0:ABC22'
end
it 'should add registrar prefix for code does not match exactly to prefix' do
response = create_request({ id: { value: 'cid2:first0:abc:ABC:11111' } })
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
Contact.last.code.should == 'FIRST0:CID2:FIRST0:ABC:ABC:11111'
end
it 'should ignore custom code when only contact prefix given' do
response = create_request({ id: { value: 'CID:FIRST0' } })
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
Contact.last.code.should =~ /FIRST0:..../
end
it 'should generate server id when id is empty' do
response = create_request({ id: nil })
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
Contact.last.code.should_not == 'registrar1:'
end
it 'should generate server id when id is empty' do
response = create_request
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
Contact.last.code.should_not == 'registrar1:'
end
it 'should return parameter value policy error for org' do
response = create_request({ postalInfo: { org: { value: 'should not save' } } })
response[:msg].should ==
'Parameter value policy error. Org must be blank: postalInfo > org [org]'
response[:result_code].should == '2306'
Contact.last.org_name.should == nil
end
it 'should return parameter value policy error for fax' do
response = create_request({ fax: { value: 'should not save' } })
response[:msg].should ==
'Parameter value policy error. Fax must be blank: fax [fax]'
response[:result_code].should == '2306'
Contact.last.fax.should == nil
end
end
context 'update command' do
before :all do
@contact =
Fabricate(
:contact,
registrar: @registrar1,
email: '[email protected]',
code: 'FIRST0:SH8013'
)
end
def update_request(overwrites = {}, extension = {}, options = {})
extension = @update_extension if extension.blank?
defaults = {
id: { value: 'asd123123er' },
chg: {
postalInfo: {
name: { value: 'John Doe Edited' }
},
voice: { value: '+372.7654321' },
fax: nil,
email: { value: '[email protected]' },
authInfo: { pw: { value: 'password' } }
}
}
update_xml = @epp_xml.update(defaults.deep_merge(overwrites), extension)
epp_plain_request(update_xml, options)
end
it 'fails if request is invalid' do
response = epp_plain_request(@epp_xml.update)
response[:results][0][:msg].should ==
"Element '{https://epp.tld.ee/schema/contact-eis-1.0.xsd}update': Missing child element(s). "\
"Expected is ( {https://epp.tld.ee/schema/contact-eis-1.0.xsd}id )."
end
it 'returns error if obj doesnt exist' do
response = update_request({ id: { value: 'not-exists' } })
response[:msg].should == 'Object does not exist'
response[:result_code].should == '2303'
response[:results].count.should == 1
end
it 'is succesful' do
response = update_request({ id: { value: 'FIRST0:SH8013' } })
response[:msg].should == 'Command completed successfully'
@contact.reload
@contact.name.should == 'John Doe Edited'
@contact.email.should == '[email protected]'
end
it 'is succesful for own contact without password' do
without_password = {
id: { value: 'FIRST0:SH8013' },
chg: {
postalInfo: {
name: { value: 'John Doe Edited' }
}
}
}
update_xml = @epp_xml.update(without_password)
response = epp_plain_request(update_xml, :xml)
response[:msg].should == 'Command completed successfully'
@contact.reload
@contact.name.should == 'John Doe Edited'
end
it 'should update other contact with correct password' do
login_as :registrar2 do
response = update_request({ id: { value: 'FIRST0:SH8013' } })
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
end
end
it 'should not update other contact without password' do
login_as :registrar2 do
without_password = {
id: { value: 'FIRST0:SH8013' },
chg: {
postalInfo: {
name: { value: 'John Doe Edited' }
}
}
}
update_xml = @epp_xml.update(without_password)
response = epp_plain_request(update_xml, :xml)
response[:msg].should == 'Authorization error'
@contact.reload
@contact.name.should == 'John Doe Edited'
end
end
it 'returns phone and email error' do
response = update_request({
id: { value: 'FIRST0:SH8013' },
chg: {
voice: { value: '123213' },
email: { value: 'wrong' }
}
})
response[:results][0][:msg].should == 'Phone nr is invalid [phone]'
response[:results][0][:result_code].should == '2005'
response[:results][1][:msg].should == 'Email is invalid [email]'
response[:results][1][:result_code].should == '2005'
end
it 'should return email issue' do
response = update_request({
id: { value: 'FIRST0:SH8013' },
chg: {
email: { value: 'legacy@wrong' }
}
})
response[:msg].should == 'Email is invalid [email]'
response[:result_code].should == '2005'
end
it 'should not update code with custom string' do
response = update_request(
{
id: { value: 'FIRST0:SH8013' },
chg: {
id: { value: 'notpossibletoupdate' }
}
}, {}
)
response[:msg].should == "Element '{https://epp.tld.ee/schema/contact-eis-1.0.xsd}id': "\
"This element is not expected."
response[:result_code].should == '2001'
@contact.reload.code.should == 'FIRST0:SH8013'
end
it 'should not be able to update ident' do
extension = {
ident: {
value: '1990-22-12',
attrs: { type: 'birthday', cc: 'US' }
},
legalDocument: {
value: 'dGVzdCBmYWlsCg==',
attrs: { type: 'pdf' }
}
}
response = update_request({ id: { value: 'FIRST0:SH8013' } }, extension)
response[:msg].should ==
'Parameter value policy error. Update of ident data not allowed [ident]'
response[:result_code].should == '2306'
Contact.find_by(code: 'FIRST0:SH8013').ident_type.should == 'priv'
end
it 'should return parameter value policy errror for org update' do
response = update_request({
id: { value: 'FIRST0:SH8013' },
chg: {
postalInfo: { org: { value: 'should not save' } }
}
})
response[:msg].should ==
'Parameter value policy error. Org must be blank: postalInfo > org [org]'
response[:result_code].should == '2306'
Contact.find_by(code: 'FIRST0:SH8013').org_name.should == nil
end
it 'should return parameter value policy errror for fax update' do
response = update_request({
id: { value: 'FIRST0:SH8013' },
chg: {
fax: { value: 'should not save' }
}
})
response[:msg].should ==
'Parameter value policy error. Fax must be blank: fax [fax]'
response[:result_code].should == '2306'
Contact.find_by(code: 'FIRST0:SH8013').fax.should == nil
end
it 'does not allow to edit statuses if policy forbids it' do
Setting.client_status_editing_enabled = false
xml = @epp_xml.update({
id: { value: 'FIRST0:SH8013' },
add: [{
_anonymus: [
{ status: { value: 'Payment overdue.', attrs: { s: 'clientDeleteProhibited', lang: 'en' } } },
{ status: { value: '', attrs: { s: 'clientUpdateProhibited' } } }
]
}]
})
response = epp_plain_request(xml)
response[:results][0][:msg].should == "Parameter value policy error. Client-side object status "\
"management not supported: status [status]"
response[:results][0][:result_code].should == '2306'
Setting.client_status_editing_enabled = true
end
it 'should update auth info' do
xml = @epp_xml.update({
id: { value: 'FIRST0:SH8013' },
chg: {
authInfo: { pw: { value: 'newpassword' } }
}
})
response = epp_plain_request(xml, :xml)
response[:results][0][:msg].should == 'Command completed successfully'
response[:results][0][:result_code].should == '1000'
contact = Contact.find_by(code: 'FIRST0:SH8013')
contact.auth_info.should == 'newpassword'
end
it 'should add value voice value' do
xml = @epp_xml.update({
id: { value: 'FIRST0:SH8013' },
chg: {
voice: { value: '+372.11111111' },
authInfo: { pw: { value: 'password' } }
}
})
response = epp_plain_request(xml, :xml)
response[:results][0][:msg].should == 'Command completed successfully'
response[:results][0][:result_code].should == '1000'
contact = Contact.find_by(code: 'FIRST0:SH8013')
contact.phone.should == '+372.11111111'
contact.update_attribute(:phone, '+372.7654321') # restore default value
end
it 'should return error when add attributes phone value is empty' do
phone = Contact.find_by(code: 'FIRST0:SH8013').phone
xml = @epp_xml.update({
id: { value: 'FIRST0:SH8013' },
chg: {
voice: { value: '' },
email: { value: '[email protected]' },
authInfo: { pw: { value: 'password' } }
}
})
response = epp_plain_request(xml, :xml)
response[:results][0][:msg].should == 'Required parameter missing - phone [phone]'
response[:results][0][:result_code].should == '2003'
Contact.find_by(code: 'FIRST0:SH8013').phone.should == phone # aka not changed
end
it 'should not allow to remove required voice attribute' do
contact = Contact.find_by(code: 'FIRST0:SH8013')
phone = contact.phone
xml = @epp_xml.update({
id: { value: 'FIRST0:SH8013' },
chg: {
voice: { value: '' },
authInfo: { pw: { value: 'password' } }
}
})
response = epp_plain_request(xml, :xml)
response[:results][0][:msg].should == 'Required parameter missing - phone [phone]'
response[:results][0][:result_code].should == '2003'
contact = Contact.find_by(code: 'FIRST0:SH8013')
contact.phone.should == phone
end
it 'should return general policy error when updating org' do
xml = @epp_xml.update({
id: { value: 'FIRST0:SH8013' },
chg: {
postalInfo: {
org: { value: 'shouldnot' }
},
authInfo: { pw: { value: 'password' } }
}
})
response = epp_plain_request(xml)
response[:results][0][:msg].should ==
'Parameter value policy error. Org must be blank: postalInfo > org [org]'
response[:results][0][:result_code].should == '2306'
end
it 'does not allow to edit statuses if policy forbids it' do
Setting.client_status_editing_enabled = false
xml = @epp_xml.update({
id: { value: 'FIRST0:SH8013' },
add: [{
_anonymus: [
{ status: { value: '', attrs: { s: 'clientUpdateProhibited' } } }
]
}]
})
response = epp_plain_request(xml)
response[:results][0][:msg].should == "Parameter value policy error. Client-side object status "\
"management not supported: status [status]"
response[:results][0][:result_code].should == '2306'
Setting.client_status_editing_enabled = true
end
end
context 'delete command' do
before do
@contact = Fabricate(:contact, registrar: @registrar1)
end
def delete_request(overwrites = {})
defaults = {
id: { value: @contact.code },
authInfo: { pw: { value: @contact.auth_info } }
}
delete_xml = @epp_xml.delete(defaults.deep_merge(overwrites), @extension)
epp_plain_request(delete_xml, :xml)
end
it 'fails if request is invalid' do
response = epp_plain_request(@epp_xml.delete)
response[:results][0][:msg].should ==
"Element '{https://epp.tld.ee/schema/contact-eis-1.0.xsd}delete': Missing child element(s). "\
"Expected is ( {https://epp.tld.ee/schema/contact-eis-1.0.xsd}id )."
response[:results][0][:result_code].should == '2001'
response[:results].count.should == 1
end
it 'returns error if obj doesnt exist' do
response = delete_request({ id: { value: 'not-exists' } })
response[:msg].should == 'Object does not exist'
response[:result_code].should == '2303'
response[:results].count.should == 1
end
it 'deletes contact' do
response = delete_request
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
response[:clTRID].should == 'ABC-12345'
Contact.find_by_id(@contact.id).should == nil
end
it 'deletes own contact even with wrong password' do
response = delete_request({ authInfo: { pw: { value: 'wrong password' } } })
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
response[:clTRID].should == 'ABC-12345'
Contact.find_by_id(@contact.id).should == nil
end
it 'deletes own contact even without password' do
delete_xml = @epp_xml.delete({ id: { value: @contact.code } })
response = epp_plain_request(delete_xml, :xml)
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
response[:clTRID].should == 'ABC-12345'
Contact.find_by_id(@contact.id).should == nil
end
it 'fails if contact has associated domain' do
@domain = Fabricate(:domain, registrar: @registrar1, registrant: Registrant.find(@contact.id))
@domain.registrant.present?.should == true
response = delete_request
response[:msg].should == 'Object association prohibits operation [domains]'
response[:result_code].should == '2305'
response[:results].count.should == 1
@domain.registrant.present?.should == true
end
it 'should delete when not owner but with correct password' do
login_as :registrar2 do
response = delete_request
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
response[:clTRID].should == 'ABC-12345'
Contact.find_by_id(@contact.id).should == nil
end
end
it 'should not delete when not owner without password' do
login_as :registrar2 do
delete_xml = @epp_xml.delete({ id: { value: @contact.code } })
response = epp_plain_request(delete_xml, :xml)
response[:msg].should == 'Authorization error'
response[:result_code].should == '2201'
response[:results].count.should == 1
end
end
it 'should not delete when not owner with wrong password' do
login_as :registrar2 do
response = delete_request({ authInfo: { pw: { value: 'wrong password' } } })
response[:msg].should == 'Authorization error'
response[:result_code].should == '2201'
response[:results].count.should == 1
end
end
end
context 'check command' do
def check_request(overwrites = {})
defaults = {
id: { value: @contact.code },
authInfo: { pw: { value: @contact.auth_info } }
}
xml = @epp_xml.check(defaults.deep_merge(overwrites))
epp_plain_request(xml, :xml)
end
it 'fails if request is invalid' do
response = epp_plain_request(@epp_xml.check)
response[:results][0][:msg].should ==
"Element '{https://epp.tld.ee/schema/contact-eis-1.0.xsd}check': Missing child element(s). "\
"Expected is ( {https://epp.tld.ee/schema/contact-eis-1.0.xsd}id )."
response[:results][0][:result_code].should == '2001'
response[:results].count.should == 1
end
it 'returns info about contact availability' do
contact = Fabricate(:contact, code: 'check-1234')
contact.code.should == 'FIXED:CHECK-1234'
response = epp_plain_request(check_multiple_contacts_xml, :xml)
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
ids = response[:parsed].css('resData chkData id')
ids[0].attributes['avail'].text.should == '0'
ids[1].attributes['avail'].text.should == '1'
ids[0].text.should == 'FIXED:CHECK-1234'
ids[1].text.should == 'check-4321'
end
it 'should support legacy CID farmat' do
contact = Fabricate(:contact, code: 'check-LEGACY')
contact.code.should == 'FIXED:CHECK-LEGACY'
response = epp_plain_request(check_multiple_legacy_contacts_xml, :xml)
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
ids = response[:parsed].css('resData chkData id')
ids[0].text.should == 'FIXED:CHECK-LEGACY'
ids[1].text.should == 'CID:FIXED:CHECK-LEGACY'
ids[0].attributes['avail'].text.should == '0'
ids[1].attributes['avail'].text.should == '1'
end
end
context 'info command' do
def info_request(overwrites = {}, options = {})
defaults = {
id: { value: @contact.code },
authInfo: { pw: { value: @contact.auth_info } }
}
xml = @epp_xml.info(defaults.deep_merge(overwrites))
epp_plain_request(xml, options)
end
it 'fails if request invalid' do
response = epp_plain_request(@epp_xml.info)
response[:results][0][:msg].should ==
"Element '{https://epp.tld.ee/schema/contact-eis-1.0.xsd}info': Missing child element(s). "\
"Expected is ( {https://epp.tld.ee/schema/contact-eis-1.0.xsd}id )."
response[:results][0][:result_code].should == '2001'
response[:results].count.should == 1
end
it 'returns error when object does not exist' do
response = info_request({ id: { value: 'no-contact' } })
response[:msg].should == 'Object does not exist'
response[:result_code].should == '2303'
response[:results][0][:value].should == 'NO-CONTACT'
response[:results].count.should == 1
end
it 'return info about contact' do
Fabricate(:contact, code: 'INFO-4444', name: 'Johnny Awesome')
response = info_request({ id: { value: 'FIXED:INFO-4444' } })
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
contact = response[:parsed].css('resData infData')
contact.css('name').first.text.should == 'Johnny Awesome'
end
it 'should add legacy CID format as append' do
Fabricate(:contact, code: 'CID:FIXED:INFO-5555', name: 'Johnny Awesome')
response = info_request({ id: { value: 'FIXED:CID:FIXED:INFO-5555' } })
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
contact = response[:parsed].css('resData infData')
contact.css('name').first.text.should == 'Johnny Awesome'
end
it 'should return ident in extension' do
@registrar1_contact = Fabricate(:contact, code: 'INFO-IDENT',
registrar: @registrar1, name: 'Johnny Awesome')
response = info_request({ id: { value: @registrar1_contact.code } })
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
contact = response[:parsed].css('resData infData')
contact.css('ident').first.should == nil # ident should be in extension
contact = response[:parsed].css('extension')
contact.css('ident').first.text.should == '37605030299'
end
it 'returns no authorization error for wrong password when registrant' do
response = info_request({ authInfo: { pw: { value: 'wrong-pw' } } })
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
response[:results].count.should == 1
end
it 'should honor new contact code format' do
@registrar1_contact = Fabricate(:contact, code: 'FIXED:test:custom:code')
@registrar1_contact.code.should == 'FIXED:TEST:CUSTOM:CODE'
response = info_request({ id: { value: 'FIXED:TEST:CUSTOM:CODE' } })
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
contact = response[:parsed].css('resData infData')
contact.css('ident').first.should == nil # ident should be in extension
contact = response[:parsed].css('extension')
contact.css('ident').first.text.should == '37605030299'
end
it 'returns no authorization error for wrong user but correct password' do
login_as :registrar2 do
response = info_request
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
response[:results].count.should == 1
contact = response[:parsed].css('resData infData')
contact.css('postalInfo addr city').first.try(:text).present?.should == true
contact.css('email').first.try(:text).present?.should == true
contact.css('voice').first.try(:text).should == '+372.12345678'
end
end
it 'returns authorization error for wrong user and wrong password' do
login_as :registrar2 do
response = info_request({ authInfo: { pw: { value: 'wrong-pw' } } })
response[:msg].should == 'Authorization error'
response[:result_code].should == '2201'
response[:results].count.should == 1
contact = response[:parsed].css('resData infData')
contact.css('postalInfo addr city').first.try(:text).should == nil
contact.css('email').first.try(:text).should == nil
contact.css('voice').first.try(:text).should == nil
end
end
it 'returns no authorization error for wrong user and no password' do
login_as :registrar2 do
response = info_request({ authInfo: { pw: { value: '' } } }, validate_output: false)
response[:msg].should == 'Command completed successfully'
response[:result_code].should == '1000'
response[:results].count.should == 1
contact = response[:parsed].css('resData infData')
contact.css('postalInfo addr city').first.try(:text).should == nil
contact.css('email').first.try(:text).should == nil
contact.css('voice').first.try(:text).should == nil
end
end
end
end
def check_multiple_contacts_xml
'<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0">
<command>
<check>
<contact:check
xmlns:contact="https://epp.tld.ee/schema/contact-eis-1.0.xsd">
<contact:id>FIXED:CHECK-1234</contact:id>
<contact:id>check-4321</contact:id>
</contact:check>
</check>
<clTRID>ABC-12345</clTRID>
</command>
</epp>'
end
def check_multiple_legacy_contacts_xml
'<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0">
<command>
<check>
<contact:check
xmlns:contact="https://epp.tld.ee/schema/contact-eis-1.0.xsd">
<contact:id>FIXED:CHECK-LEGACY</contact:id>
<contact:id>CID:FIXED:CHECK-LEGACY</contact:id>
</contact:check>
</check>
<clTRID>ABC-12345</clTRID>
</command>
</epp>'
end
end
| 35.855649 | 108 | 0.582619 |
4aeb9443e6d8ad3ecec6e7d608fc32c709875e3f | 360 | cask 'font-iceland' do
version '1.001'
sha256 '5b5919189e5d01a6fac79251aaf9fa9565a738c39974cbe13de98ac02ec7fff5'
url 'https://googlefontdirectory.googlecode.com/hg-history/67342bc472599b4c32201ee4a002fe59a6447a42/ofl/iceland/Iceland-Regular.ttf'
homepage 'http://www.google.com/fonts/specimen/Iceland'
license :ofl
font 'Iceland-Regular.ttf'
end
| 32.727273 | 134 | 0.811111 |
ac93c4b10e046fb44158c9e6e5b14908887e6c17 | 1,334 | # encoding: utf-8
# This file is distributed under New Relic's license terms.
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
# This class acts like an Array with a fixed capacity that randomly samples
# from a stream of items such that the probability of each item being included
# in the Array is equal. It uses reservoir sampling in order to achieve this:
# http://xlinux.nist.gov/dads/HTML/reservoirSampling.html
require 'new_relic/agent/event_buffer'
module NewRelic
module Agent
class SampledBuffer < EventBuffer
attr_reader :seen_lifetime, :captured_lifetime
def initialize(capacity)
super
@captured_lifetime = 0
@seen_lifetime = 0
end
def reset!
@captured_lifetime += @items.size
@seen_lifetime += @seen
super
end
def append_event(x)
if @items.size < @capacity
@items << x
return x
else
m = rand(@seen) # [0, @seen)
if m < @capacity
@items[m] = x
return x
else
# discard current sample
return nil
end
end
end
def sample_rate_lifetime
@captured_lifetime > 0 ? (@captured_lifetime.to_f / @seen_lifetime) : 0.0
end
end
end
end
| 25.653846 | 81 | 0.616192 |
f7324c7c2f27b16ac9dc5bbc34b7d3118641883b | 481 | require 'pancake'
require ::File.join(::File.expand_path(::File.dirname(__FILE__)), "..", "blog")
# get the application to run. The applicadtion in the Pancake.start block
# is the master application. It will have all requests directed to it through the
# pancake middleware
# This should be a very minimal file, but should be used when any stand alone code needs to be included
app = Pancake.start(:root => Pancake.get_root(__FILE__)){ Blog.stackup(:master => true) }
run app
| 43.727273 | 103 | 0.744283 |
7a8e913fd767ea7a3dc294e8199fe8af8ece0050 | 5,168 | #!/usr/bin/env ruby
require 'stringio'
require 'tmpdir'
require_relative '../lib/messages'
require_relative '../lib/parsing/properties_reader'
require_relative '../lib/parsing/parser'
require_relative '../lib/domain/presentation'
require_relative '../lib/rendering/renderer_html_presentation'
require_relative '../lib/rendering/renderer_html_plain'
require_relative '../lib/rendering/renderer_latex_presentation'
require_relative '../lib/rendering/renderer_latex_plain'
require_relative '../lib/rendering/renderer_jekyll'
$project_path = ''
##
# Main entry point into the markdown compiler.
# The +self.main+ method is called with the command
# line parameters.
class Main
def self.check_element(container)
result = false
container.each do |element|
if element.is_a?(Domain::Comment)
result |= check_element(element)
end
if element.is_a?(Domain::Equation)
return true
end
if element.to_s =~ /\\\[(.*?)\\\]/
return true
end
end
result
end
def self.has_equation(chapters)
chapters.each do |chapter|
chapter.each do |slides|
slides.each do |slide|
return true if check_element(slide)
end
end
end
false
end
def self.main(directory, result_dir)
# Determine my own directory to make invocation of the UML tool
# more dynamic
$project_path = File.expand_path($PROGRAM_NAME)
.tr('\\', '/')
.gsub('/mdc/bin/jekyll.rb', '')
# Read global properties
dir = Dir.new(directory)
prop_file = directory + '/metadata.properties'
defaults_file = directory + '/..' + '/metadata.properties'
props = Parsing::PropertiesReader.new(prop_file, '=', defaults_file)
title1 = props['title_1']
title2 = props['title_2']
chapter_no = props['chapter_no']
chapter_name = props['chapter_name']
copyright = props['copyright']
author = props['author']
default_syntax = props['default_syntax']
image_dir = props['image_dir']
temp_dir = props['temp_dir']
description = props['description']
term = props['term']
slide_language = props['language']
bibliography = props['bibliography']
create_index = (props['create_index'] || 'false') == 'true'
temp_dir ||= Dir.tmpdir
slide_language ||= 'DE'
set_language(slide_language.downcase)
image_dir = image_dir.sub(%r{/$}, '') unless image_dir.nil?
temp_dir = temp_dir.sub(%r{/$}, '') unless temp_dir.nil?
# Scan files matching the pattern 01_...
files = []
dir.each { |file| files << file if /[0-9][0-9]_.*\.md/ =~ file }
files = files.sort
puts "Directory: #{directory}"
chapters = []
# Parse files in directory and render result
files.each_with_index do |file, nav_order|
parser = Parsing::Parser.new(Constants::PAGES_FRONT_MATTER)
presentation = Domain::Presentation.new(
slide_language, title1, title2, chapter_no, chapter_name,
copyright, author, default_syntax, description,
term, create_index, bibliography
)
chapters << presentation.chapters
puts "Parsing: #{file}"
parser.parse(directory + '/' + file, default_syntax, presentation)
parser.second_pass(presentation)
has_equation = has_equation(chapters)
io = StringIO.new
io.set_encoding('UTF-8')
output_file = result_dir + "/" + File.basename(file, ".md") + ".markdown"
renderer = Rendering::RendererJekyll.new(
io, default_syntax, result_dir,
image_dir, temp_dir, nav_order + 1, has_equation)
puts "Result written to: #{output_file}"
presentation >> renderer
File.open(output_file, 'w', encoding: 'UTF-8') { |f| f << io.string }
end
# Write index file
File.open(result_dir + "/" + "index.markdown", 'w', encoding: 'UTF-8') do |f|
f << "---\n"
f << "title: #{chapter_name}\n"
f << "layout: default\n"
f << "has_children: true\n"
f << "has_toc: true\n"
f << "nav_order: #{chapter_no}\n"
f << "---\n"
f << "\n"
f << "# #{chapter_name}\n"
end
# Write welcome file
File.open(result_dir + "/../" + "index.markdown", 'w', encoding: 'UTF-8') do |f|
nl = "\n"
f << %Q|---| << nl
f << %Q|layout: home| << nl
f << %Q|---| << nl
f << %Q|| << nl
f << %Q|<div class="text-purple-200 fs-6 fw-700">#{title1}</div>| << nl
f << %Q|<div class="fs-4 fw-700">#{title2}</div>| << nl
f << %Q|<div>#{term}</div>| << nl
f << %Q|<div class="fs-3 fw-300">Stand: #{Time.new.strftime("%d.%m.%Y")}</div>| << nl
#f << %Q|<br>| << nl
#f << %Q|<div class="fs-4 fw-500">#{copyright}</div>| << nl
f << %Q|<br>| << nl
f << %Q|<div class="text-grey-dk-000 fs-2 fw-300">#{description}</div>| << nl
end
end
end
Main.main(ARGV[0], ARGV[1])
# Main::main('/Users/thomas/Documents/Work/Vorlesungen/GDI/03_Folien/src/06_oo',
# 'tex-plain', '/Users/thomas/Temp/06_oo/06_oo.tex')
| 30.761905 | 91 | 0.596749 |
ff8aa687888cb7d7b52c586eeece1ac5252022e9 | 51 | class PdfboxTextExtraction
VERSION = "1.2.0"
end
| 12.75 | 26 | 0.745098 |
6a78b10b1f40896bf645aa48f4154e696ffe4248 | 1,487 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Subscriptions::Mgmt::V2019_10_01_preview
module Models
#
# REST API operation
#
class Operation
include MsRestAzure
# @return [String] Operation name: {provider}/{resource}/{operation}
attr_accessor :name
# @return [OperationDisplay] The object that represents the operation.
attr_accessor :display
#
# Mapper for Operation class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'Operation',
type: {
name: 'Composite',
class_name: 'Operation',
model_properties: {
name: {
client_side_validation: true,
required: false,
serialized_name: 'name',
type: {
name: 'String'
}
},
display: {
client_side_validation: true,
required: false,
serialized_name: 'display',
type: {
name: 'Composite',
class_name: 'OperationDisplay'
}
}
}
}
}
end
end
end
end
| 25.637931 | 76 | 0.517149 |
21fcc1e456f41008280147ccab0fb521b2825ee0 | 738 | # frozen_string_literal: true
require 'splunk-sdk-ruby'
require 'uri'
require 'splunk/pickaxe/config'
require 'splunk/pickaxe/client'
require 'splunk/pickaxe/cookie_proxy'
module Splunk
module Pickaxe
def self.configure(environment, username, password, args)
config = Config.load(environment, args.fetch(:repo_path, Dir.getwd))
uri = URI(config.url)
puts "Connecting to splunk [#{uri}]"
service = Splunk.connect(
proxy: CookieProxy,
scheme: uri.scheme.to_sym,
host: uri.host,
port: uri.port,
username: username,
password: password,
namespace: config.namespace
)
Client.new service, environment.downcase, config, args
end
end
end
| 23.806452 | 74 | 0.668022 |
01c074944762a35d806e86a7a6a04a6837013bfd | 976 | cask '[email protected]' do
version '2017.4.9f1,6d84dfc57ccf'
sha256 :no_check
url "https://download.unity3d.com/download_unity/6d84dfc57ccf/MacExampleProjectInstaller/Examples.pkg"
name 'Example Project'
homepage 'https://unity3d.com/unity/'
pkg 'Examples.pkg'
depends_on cask: '[email protected]'
preflight do
if File.exist? "/Applications/Unity"
FileUtils.move "/Applications/Unity", "/Applications/Unity.temp"
end
if File.exist? "/Applications/Unity-2017.4.9f1"
FileUtils.move "/Applications/Unity-2017.4.9f1", '/Applications/Unity'
end
end
postflight do
if File.exist? '/Applications/Unity'
FileUtils.move '/Applications/Unity', "/Applications/Unity-2017.4.9f1"
end
if File.exist? '/Applications/Unity.temp'
FileUtils.move '/Applications/Unity.temp', '/Applications/Unity'
end
end
uninstall quit: 'com.unity3d.UnityEditor5.x',
delete: '/Users/Shared/Unity'
end
| 27.111111 | 104 | 0.697746 |
618c6b03723ea3a76b33c3c7a0b3257989e9f7b1 | 43 | module FyntechFeed
VERSION = "0.1.3"
end
| 10.75 | 19 | 0.697674 |
1cd3364dc3141fd26c6e8d5557e2cf7e039abc1a | 31,403 | require 'spec_helper'
describe Pubnub::Heartbeat do
around :each do |example|
Celluloid.boot
@fired = false
@callback = ->(_envelope) do
@fired = true
end
@pubnub = Pubnub.new(
publish_key: 'pub-c-b42cec2f-f468-4784-8833-dd2b074538c4',
subscribe_key: 'sub-c-b7fb805a-1777-11e6-be83-0619f8945a4f',
uuid: 'ruby-test-uuid-client-one',
auth_key: 'ruby-test-auth-client-one'
)
example.run
Celluloid.shutdown
end
it '__channel___demo___channel_group___demo___http_sync__true___callback__nil_' do
VCR.use_cassette('examples/heartbeat/29', record: :none) do
envelope = @pubnub.heartbeat(channel: :demo, channel_group: :demo, http_sync: true)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo___channel_group___demo___http_sync__true___callback___block_' do
VCR.use_cassette('examples/heartbeat/27', record: :none) do
envelope = @pubnub.heartbeat(channel: :demo, channel_group: :demo, http_sync: true, &@callback)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo___channel_group___demo___http_sync__true___callback___lambda_' do
VCR.use_cassette('examples/heartbeat/28', record: :none) do
envelope = @pubnub.heartbeat(channel: :demo, channel_group: :demo, http_sync: true, callback: @callback)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo___channel_group___demo___http_sync__false___callback__nil_' do
VCR.use_cassette('examples/heartbeat/26', record: :none) do
envelope = @pubnub.heartbeat(channel: :demo, channel_group: :demo, http_sync: false)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo___channel_group___demo___http_sync__false___callback___block_' do
VCR.use_cassette('examples/heartbeat/24', record: :none) do
envelope = @pubnub.heartbeat(channel: :demo, channel_group: :demo, http_sync: false, &@callback)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo___channel_group___demo___http_sync__false___callback___lambda_' do
VCR.use_cassette('examples/heartbeat/25', record: :none) do
envelope = @pubnub.heartbeat(channel: :demo, channel_group: :demo, http_sync: false, callback: @callback)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo___channel_group___demo____http_sync__true___callback__nil_' do
VCR.use_cassette('examples/heartbeat/23', record: :none) do
envelope = @pubnub.heartbeat(channel: :demo, channel_group: 'demo', http_sync: true)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo___channel_group___demo____http_sync__true___callback___block_' do
VCR.use_cassette('examples/heartbeat/21', record: :none) do
envelope = @pubnub.heartbeat(channel: :demo, channel_group: 'demo', http_sync: true, &@callback)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo___channel_group___demo____http_sync__true___callback___lambda_' do
VCR.use_cassette('examples/heartbeat/22', record: :none) do
envelope = @pubnub.heartbeat(channel: :demo, channel_group: 'demo', http_sync: true, callback: @callback)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo___channel_group___demo____http_sync__false___callback__nil_' do
VCR.use_cassette('examples/heartbeat/20', record: :none) do
envelope = @pubnub.heartbeat(channel: :demo, channel_group: 'demo', http_sync: false)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo___channel_group___demo____http_sync__false___callback___block_' do
VCR.use_cassette('examples/heartbeat/18', record: :none) do
envelope = @pubnub.heartbeat(channel: :demo, channel_group: 'demo', http_sync: false, &@callback)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo___channel_group___demo____http_sync__false___callback___lambda_' do
VCR.use_cassette('examples/heartbeat/19', record: :none) do
envelope = @pubnub.heartbeat(channel: :demo, channel_group: 'demo', http_sync: false, callback: @callback)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo___channel_group__nil___http_sync__true___callback__nil_' do
VCR.use_cassette('examples/heartbeat/35', record: :none) do
envelope = @pubnub.heartbeat(channel: :demo, http_sync: true)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo___channel_group__nil___http_sync__true___callback___block_' do
VCR.use_cassette('examples/heartbeat/33', record: :none) do
envelope = @pubnub.heartbeat(channel: :demo, http_sync: true, &@callback)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo___channel_group__nil___http_sync__true___callback___lambda_' do
VCR.use_cassette('examples/heartbeat/34', record: :none) do
envelope = @pubnub.heartbeat(channel: :demo, http_sync: true, callback: @callback)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo___channel_group__nil___http_sync__false___callback__nil_' do
VCR.use_cassette('examples/heartbeat/32', record: :none) do
envelope = @pubnub.heartbeat(channel: :demo, http_sync: false)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo___channel_group__nil___http_sync__false___callback___block_' do
VCR.use_cassette('examples/heartbeat/30', record: :none) do
envelope = @pubnub.heartbeat(channel: :demo, http_sync: false, &@callback)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo___channel_group__nil___http_sync__false___callback___lambda_' do
VCR.use_cassette('examples/heartbeat/31', record: :none) do
envelope = @pubnub.heartbeat(channel: :demo, http_sync: false, callback: @callback)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo____channel_group___demo___http_sync__true___callback__nil_' do
VCR.use_cassette('examples/heartbeat/11', record: :none) do
envelope = @pubnub.heartbeat(channel: 'demo', channel_group: :demo, http_sync: true)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo____channel_group___demo___http_sync__true___callback___block_' do
VCR.use_cassette('examples/heartbeat/9', record: :none) do
envelope = @pubnub.heartbeat(channel: 'demo', channel_group: :demo, http_sync: true, &@callback)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo____channel_group___demo___http_sync__true___callback___lambda_' do
VCR.use_cassette('examples/heartbeat/10', record: :none) do
envelope = @pubnub.heartbeat(channel: 'demo', channel_group: :demo, http_sync: true, callback: @callback)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo____channel_group___demo___http_sync__false___callback__nil_' do
VCR.use_cassette('examples/heartbeat/8', record: :none) do
envelope = @pubnub.heartbeat(channel: 'demo', channel_group: :demo, http_sync: false)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo____channel_group___demo___http_sync__false___callback___block_' do
VCR.use_cassette('examples/heartbeat/6', record: :none) do
envelope = @pubnub.heartbeat(channel: 'demo', channel_group: :demo, http_sync: false, &@callback)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo____channel_group___demo___http_sync__false___callback___lambda_' do
VCR.use_cassette('examples/heartbeat/7', record: :none) do
envelope = @pubnub.heartbeat(channel: 'demo', channel_group: :demo, http_sync: false, callback: @callback)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo____channel_group___demo____http_sync__true___callback__nil_' do
VCR.use_cassette('examples/heartbeat/5', record: :none) do
envelope = @pubnub.heartbeat(channel: 'demo', channel_group: 'demo', http_sync: true)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo____channel_group___demo____http_sync__true___callback___block_' do
VCR.use_cassette('examples/heartbeat/3', record: :none) do
envelope = @pubnub.heartbeat(channel: 'demo', channel_group: 'demo', http_sync: true, &@callback)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo____channel_group___demo____http_sync__true___callback___lambda_' do
VCR.use_cassette('examples/heartbeat/4', record: :none) do
envelope = @pubnub.heartbeat(channel: 'demo', channel_group: 'demo', http_sync: true, callback: @callback)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo____channel_group___demo____http_sync__false___callback__nil_' do
VCR.use_cassette('examples/heartbeat/2', record: :none) do
envelope = @pubnub.heartbeat(channel: 'demo', channel_group: 'demo', http_sync: false)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo____channel_group___demo____http_sync__false___callback___block_' do
VCR.use_cassette('examples/heartbeat/0', record: :none) do
envelope = @pubnub.heartbeat(channel: 'demo', channel_group: 'demo', http_sync: false, &@callback)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo____channel_group___demo____http_sync__false___callback___lambda_' do
VCR.use_cassette('examples/heartbeat/1', record: :none) do
envelope = @pubnub.heartbeat(channel: 'demo', channel_group: 'demo', http_sync: false, callback: @callback)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo____channel_group__nil___http_sync__true___callback__nil_' do
VCR.use_cassette('examples/heartbeat/17', record: :none) do
envelope = @pubnub.heartbeat(channel: 'demo', http_sync: true)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo____channel_group__nil___http_sync__true___callback___block_' do
VCR.use_cassette('examples/heartbeat/15', record: :none) do
envelope = @pubnub.heartbeat(channel: 'demo', http_sync: true, &@callback)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo____channel_group__nil___http_sync__true___callback___lambda_' do
VCR.use_cassette('examples/heartbeat/16', record: :none) do
envelope = @pubnub.heartbeat(channel: 'demo', http_sync: true, callback: @callback)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo____channel_group__nil___http_sync__false___callback__nil_' do
VCR.use_cassette('examples/heartbeat/14', record: :none) do
envelope = @pubnub.heartbeat(channel: 'demo', http_sync: false)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo____channel_group__nil___http_sync__false___callback___block_' do
VCR.use_cassette('examples/heartbeat/12', record: :none) do
envelope = @pubnub.heartbeat(channel: 'demo', http_sync: false, &@callback)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel___demo____channel_group__nil___http_sync__false___callback___lambda_' do
VCR.use_cassette('examples/heartbeat/13', record: :none) do
envelope = @pubnub.heartbeat(channel: 'demo', http_sync: false, callback: @callback)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel__nil___channel_group___demo___http_sync__true___callback__nil_' do
VCR.use_cassette('examples/heartbeat/47', record: :none) do
envelope = @pubnub.heartbeat(channel_group: :demo, http_sync: true)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel__nil___channel_group___demo___http_sync__true___callback___block_' do
VCR.use_cassette('examples/heartbeat/45', record: :none) do
envelope = @pubnub.heartbeat(channel_group: :demo, http_sync: true, &@callback)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel__nil___channel_group___demo___http_sync__true___callback___lambda_' do
VCR.use_cassette('examples/heartbeat/46', record: :none) do
envelope = @pubnub.heartbeat(channel_group: :demo, http_sync: true, callback: @callback)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel__nil___channel_group___demo___http_sync__false___callback__nil_' do
VCR.use_cassette('examples/heartbeat/44', record: :none) do
envelope = @pubnub.heartbeat(channel_group: :demo, http_sync: false)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel__nil___channel_group___demo___http_sync__false___callback___block_' do
VCR.use_cassette('examples/heartbeat/42', record: :none) do
envelope = @pubnub.heartbeat(channel_group: :demo, http_sync: false, &@callback)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel__nil___channel_group___demo___http_sync__false___callback___lambda_' do
VCR.use_cassette('examples/heartbeat/43', record: :none) do
envelope = @pubnub.heartbeat(channel_group: :demo, http_sync: false, callback: @callback)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel__nil___channel_group___demo____http_sync__true___callback__nil_' do
VCR.use_cassette('examples/heartbeat/41', record: :none) do
envelope = @pubnub.heartbeat(channel_group: 'demo', http_sync: true)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel__nil___channel_group___demo____http_sync__true___callback___block_' do
VCR.use_cassette('examples/heartbeat/39', record: :none) do
envelope = @pubnub.heartbeat(channel_group: 'demo', http_sync: true, &@callback)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel__nil___channel_group___demo____http_sync__true___callback___lambda_' do
VCR.use_cassette('examples/heartbeat/40', record: :none) do
envelope = @pubnub.heartbeat(channel_group: 'demo', http_sync: true, callback: @callback)
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel__nil___channel_group___demo____http_sync__false___callback__nil_' do
VCR.use_cassette('examples/heartbeat/38', record: :none) do
envelope = @pubnub.heartbeat(channel_group: 'demo', http_sync: false)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel__nil___channel_group___demo____http_sync__false___callback___block_' do
VCR.use_cassette('examples/heartbeat/36', record: :none) do
envelope = @pubnub.heartbeat(channel_group: 'demo', http_sync: false, &@callback)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
it '__channel__nil___channel_group___demo____http_sync__false___callback___lambda_' do
VCR.use_cassette('examples/heartbeat/37', record: :none) do
envelope = @pubnub.heartbeat(channel_group: 'demo', http_sync: false, callback: @callback)
envelope = envelope.value
expect(envelope.is_a?(Pubnub::Envelope)).to eq true
expect(envelope.error?).to eq false
expect(envelope.status[:code]).to eq(200)
expect(envelope.status[:operation]).to eq(:heartbeat)
expect(envelope.status[:category]).to eq(:ack)
expect(envelope.status[:config]).to eq({:tls=>false, :uuid=>"ruby-test-uuid-client-one", :auth_key=>"ruby-test-auth-client-one", :origin=>"ps.pndsn.com"})
end
end
end
| 38.436965 | 154 | 0.762602 |
7a89b5bb90cdaddae5d61d5b668477774251510f | 367 | cask 'katalon-studio' do
version '7.0.4'
sha256 '697b890b70698e7222226c2f8235a65261d22c7eff851e27ab6642691764266e'
url "https://download.katalon.com/#{version}/Katalon%20Studio.dmg"
appcast 'https://github.com/katalon-studio/katalon-studio/releases.atom'
name 'Katalon Studio'
homepage 'https://www.katalon.com/download/'
app 'Katalon Studio.app'
end
| 30.583333 | 75 | 0.768392 |
1c8e40ae81b6cad61826ca09370b195c65cb0812 | 139 | # frozen_string_literal: true
# rubocop:disable Lint/Void
1
def foobar
2
3; 4; 5
6
end
7
8
9
10
# rubocop:enable Lint/Void
| 5.791667 | 29 | 0.654676 |
187fbab613581a056e53a80a19d66159cfe8d305 | 258 | # frozen_string_literal: true
class ApplicationService
def self.call(*args, &block)
instance = new(*args, &block)
instance.call
end
def call
raise NotImplementedError('Services must implement call')
end
private_class_method :new
end
| 17.2 | 61 | 0.728682 |
1d78f2498383b0d05317bbb79b941420ad845f1a | 299 | Rails.application.config.generators do |g|
g.template_engine :haml
g.helper false
g.javascripts false
g.stylesheets false
g.decorator false
g.helper_specs false
g.view_specs false
g.factory_bot dir: 'spec/factories', suffix: 'factory'
end
| 24.916667 | 61 | 0.648829 |
1ce0e6aea00943e4d390b0f6743959a150568bb8 | 464 | require 'rails_helper'
RSpec.describe Identity, type: :model do
before { @identity = FactoryGirl.build :identity }
subject { @identity }
# response specs
it { should respond_to :uid }
it { should respond_to :provider }
it { should respond_to :user_id }
# validation specs
it { should validate_presence_of :uid }
it { should validate_presence_of :provider }
# association spec
it { should belong_to :user }
it { should be_valid }
end
| 21.090909 | 52 | 0.702586 |
624a66e832220ff8442a22bee4b5098a1da05b17 | 1,449 | lib = File.expand_path("lib", __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "rulers/version"
Gem::Specification.new do |spec|
spec.name = "rulers"
spec.version = Rulers::VERSION
spec.authors = ["Toni"]
spec.email = ["[email protected]"]
spec.summary = %q{Rails clone}
# spec.description = %q{TODO: Write a longer description or delete this line.}
spec.homepage = "https://github.com/tonidezman/Ruby-on-Rulers"
spec.license = "MIT"
# spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = "https://github.com/tonidezman/Ruby-on-Rulers"
spec.metadata["changelog_uri"] = "https://github.com/tonidezman/Ruby-on-Rulers"
# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 2.0"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "minitest", "~> 5.0"
end
| 41.4 | 87 | 0.665286 |
18c2b02cd73483b816f01eba46b5b816402baa8a | 1,282 | require 'rails_admin/engine'
require 'rails_admin/abstract_model'
require 'rails_admin/config'
require 'rails_admin/extension'
require 'rails_admin/extensions/cancan'
require 'rails_admin/extensions/paper_trail'
require 'rails_admin/extensions/history'
require 'rails_admin/support/csv_converter'
require 'rails_admin/support/core_extensions'
module RailsAdmin
# Setup RailsAdmin
#
# Given the first argument is a model class, a model class name
# or an abstract model object proxies to model configuration method.
#
# If only a block is passed it is stored to initializer stack to be evaluated
# on first request in production mode and on each request in development. If
# initialization has already occured (in other words RailsAdmin.setup has
# been called) the block will be added to stack and evaluated at once.
#
# Otherwise returns RailsAdmin::Config class.
#
# @see RailsAdmin::Config
def self.config(entity = nil, &block)
if entity
RailsAdmin::Config.model(entity, &block)
elsif block_given? && ENV['SKIP_RAILS_ADMIN_INITIALIZER'] != "true"
block.call(RailsAdmin::Config)
else
RailsAdmin::Config
end
end
# Reset RailsAdmin configuration to defaults
def self.reset
RailsAdmin::Config.reset
end
end
| 32.05 | 79 | 0.75507 |
1d4b9b3eb3ea47f0e2339ded753fcc25de14c633 | 6,400 | =begin
#TransferZero API
#Reference documentation for the TransferZero API V1
OpenAPI spec version: 1.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 4.0.0-beta3
=end
require 'date'
module TransferZero
class TransactionWebhook
# The ID of the webhook that was used to send out this callback
attr_accessor :webhook
# The event that triggered this webhook
attr_accessor :event
attr_accessor :object
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'webhook' => :'webhook',
:'event' => :'event',
:'object' => :'object'
}
end
# Attribute type mapping.
def self.openapi_types
{
:'webhook' => :'String',
:'event' => :'String',
:'object' => :'Transaction'
}
end
# List of class defined in allOf (OpenAPI v3)
def self.openapi_all_of
[
:'Webhook'
]
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `TransferZero::TransactionWebhook` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `TransferZero::TransactionWebhook`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'webhook')
self.webhook = attributes[:'webhook']
end
if attributes.key?(:'event')
self.event = attributes[:'event']
end
if attributes.key?(:'object')
self.object = attributes[:'object']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
if @webhook.nil?
invalid_properties.push('invalid value for "webhook", webhook cannot be nil.')
end
if @event.nil?
invalid_properties.push('invalid value for "event", event cannot be nil.')
end
if @object.nil?
invalid_properties.push('invalid value for "object", object cannot be nil.')
end
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
return false if @webhook.nil?
return false if @event.nil?
return false if @object.nil?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
webhook == o.webhook &&
event == o.event &&
object == o.object
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[webhook, event, object].hash
end
require 'active_support/core_ext/hash'
require 'active_support/hash_with_indifferent_access.rb'
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end # or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
temp_model = TransferZero.const_get(type).new
temp_model.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
next if value.nil?
hash[param] = _to_hash(value)
end
::ActiveSupport::HashWithIndifferentAccess.new(hash)
end
def [](key)
to_hash[key]
end
def dig(*args)
to_hash.dig(*args)
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 26.122449 | 208 | 0.676094 |
3936357ef39931f3ae141143a3b38869a9bd0da7 | 706 | # frozen_string_literal: true
require "rails_helper"
RSpec.describe Aggregate::Contracts::HashMinLength do
describe "#valid?" do
it "is true if the hash is equal to min length" do
contract = Aggregate::Contracts::HashMinLength.new(2)
expect(contract.valid?(one: :one, two: :two)).to eq true
end
it "is true if the hash greater than min length" do
contract = Aggregate::Contracts::HashMinLength.new(2)
expect(contract.valid?(one: :one, two: :two, three: :three)).to eq true
end
it "is false if the hash less than min length" do
contract = Aggregate::Contracts::HashMinLength.new(2)
expect(contract.valid?(one: :one)).to eq false
end
end
end
| 33.619048 | 77 | 0.685552 |
b99d503ce3b4d3098f3e850cc9acb17637b44ce1 | 3,114 | #!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2011, Google Inc. All Rights Reserved.
#
# License:: 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.
#
# This example updates the descriptions of all active labels by updating its
# description. To determine which labels exist, run get_all_labels.rb.
#
# This feature is only available to Ad Manager premium solution networks.
require 'ad_manager_api'
def update_labels(ad_manager)
# Get the LabelService.
label_service = ad_manager.service(:LabelService, API_VERSION)
# Create a statement to only select active labels.
statement = ad_manager.new_statement_builder do |sb|
sb.where = 'isActive = :is_active'
sb.with_bind_variable('is_active', true)
end
page = {:total_result_set_size => 0}
begin
# Get labels by statement.
page = label_service.get_labels_by_statement(statement.to_statement())
if page[:results].to_a.size > 0
# Update each local label object by changing its description.
page[:results].each do |label|
label[:description] = 'This label was updated'
end
# Update the labels on the server.
updated_labels = label_service.update_labels(labels)
if updated_labels.to_a.size > 0
updated_labels.each do |label|
puts('Label ID %d and name "%s" was updated with description "%s".') %
[label[:id], label[:name], label[:description]]
end
else
puts 'No labels were updated.'
end
else
puts 'No labels were found to update.'
end
# Increase the statement offset by the page size to get the next page.
statement.offset += statement.limit
end while statement.offset < page[:total_result_set_size]
end
if __FILE__ == $0
API_VERSION = :v201802
# Get AdManagerApi instance and load configuration from ~/ad_manager_api.yml.
ad_manager = AdManagerApi::Api.new
# To enable logging of SOAP requests, set the log_level value to 'DEBUG' in
# the configuration file or provide your own logger:
# ad_manager.logger = Logger.new('ad_manager_xml.log')
begin
update_labels(ad_manager)
# HTTP errors.
rescue AdsCommon::Errors::HttpError => e
puts "HTTP Error: %s" % e
# API errors.
rescue AdManagerApi::Errors::ApiException => e
puts "Message: %s" % e.message
puts 'Errors:'
e.errors.each_with_index do |error, index|
puts "\tError [%d]:" % (index + 1)
error.each do |field, value|
puts "\t\t%s: %s" % [field, value]
end
end
end
end
| 32.4375 | 80 | 0.677906 |
e9622b8427c58dec0e92c9c997d21b4d876faf2b | 118 | require "test_helper"
class ViewTest < ActiveSupport::TestCase
# test "the truth" do
# assert true
# end
end
| 14.75 | 40 | 0.694915 |
6a0bf11203e2f6ca09c734d818293004a95c78db | 726 | class Guest < ApplicationRecord
validates :color, format: { with: /[0-9A-Fa-f]{6}/ }, allow_nil: true
validates :name,
presence: true,
uniqueness: { case_sensitive: false },
format: { with: /\A[a-zA-Z0-9 ]+\z/ }
before_validation :add_color, on: :create
after_initialize :add_color if :new_record?
before_validation :add_image, on: :create
after_initialize :add_image if :new_record?
private
def add_color
return nil unless color.blank?
self.color = ''
3.times.each { self.color += '%02X' % Random.rand(0..255) }
end
def add_image
return nil unless image_number.blank? || image_number.zero?
self.image_number = Random.rand(0..100)
end
end
| 25.034483 | 71 | 0.651515 |
f759b798ecb102fc971ce50138c9ca9311dc44a0 | 1,583 | require 'simple_health_check/base'
require 'simple_health_check/basic_status_check'
module SimpleHealthCheck
%w[ generic_check http_endpoint_check json_file mysql_check redis_check s3_check version_check version].each do |file|
classified_string = file.split('_').collect!{ |w| w.capitalize }.join
autoload classified_string.to_sym, "simple_health_check/#{file}"
end
end
require "simple_health_check/configuration"
require "simple_health_check/engine"
module SimpleHealthCheck
class Response
def initialize
@body = {}
@status = :ok
end
def add name:, status:
@body[name] = status
end
def status_code
@status || :ok
end
def status_code= val
@status = val
end
alias_method :status=, :status_code=
alias_method :status, :status_code
def body
@body
end
end
class << self
def run_checks
response = SimpleHealthCheck::Response.new
overall_status = :ok
SimpleHealthCheck::Configuration.all_checks.each_with_object(response) do |check, obj|
begin
rv = check.call(response: obj)
if rv.status.to_s != 'ok' && check.should_hard_fail?
overall_status = rv.status
end
rescue # catch the error and try to log, but keep going finish all checks
response.add name: "#{check.service_name}_severe_error", status: $ERROR_INFO.to_s
Rails.logger.error "simple_health_check gem ERROR: #{$ERROR_INFO}"
end
end
response.status = overall_status
response
end
end
end
| 25.532258 | 120 | 0.6753 |
1da95db7a546e503a7e13ec1adc36a9d4b48f016 | 318 | # == Schema Information
#
# Table name: adresses
#
# id :integer not null, primary key
# value :string(255)
# user_id :integer
# created_at :datetime
# updated_at :datetime
#
# Indexes
#
# index_adresses_on_user_id (user_id)
#
class Adresse < ActiveRecord::Base
belongs_to :user
end
| 16.736842 | 53 | 0.654088 |
033b4d5ed4ad4a72fee5fbdffcbd6c1ef3e39aab | 1,173 | module HttpSender
require 'typhoeus/adapters/faraday'
# 连接
def connection(timeout = 60, open_timeout = 60)
@connection ||= Faraday.new( ssl: { verify: false } ) do |conn|
conn.request :multipart
conn.request :url_encoded
conn.request :retry, max: 0, interval: 0.05,
interval_randomness: 0.5, backoff_factor: 2,
exceptions: [Faraday::TimeoutError, Timeout::Error]
conn.response :logger
conn.adapter :typhoeus
conn.options.timeout = timeout
conn.options.open_timeout = open_timeout
end
end
def send_get_req(url, path, timeout = 60, open_timeout = 60, res_format = 'json')
@connection ||= connection(timeout, open_timeout)
begin
res = @connection.get do |req|
req.url (url + path)
req.options.timeout = timeout
req.options.open_timeout = open_timeout
end
if res_format == 'json'
JSON.parse(res.body)
elsif res_format == 'xml'
Helper.xml_str_to_hash(res.body)
else
res.body
end
rescue Exception => exception
{ message: exception.message }
end
end
end | 27.928571 | 83 | 0.616368 |
e9f0995d43736c3e6e40ca9f7e67a0dde99e229c | 246 | require 'zbozi_api_ruby/responses/base'
module ZboziApiRuby
module Response
class MarkGettingReadyForPickup < Base
attr_reader :expected_delivery_date
def initialize(json)
super(json)
end
end
end
end
| 17.571429 | 42 | 0.695122 |
bf216bc60d1d6fd043f35f0ffbd83918ff105f9b | 3,036 | package ['git', 'maven']
# In EE hopsworks is copied from the local node into the VM with the vagrantfile
if node['build']['test']['community']
# Clone Hopsworks
git node['test']['hopsworks']['base_dir'] do
repository node['test']['hopsworks']['repo']
revision node['test']['hopsworks']['branch']
user "vagrant"
group "vagrant"
action :sync
end
end
# Create chef-solo cache dir
directory '/tmp/chef-solo' do
owner 'root'
group 'root'
mode '0755'
action :create
end
#EE default flags
ubuntu_build_flags = "-Premote-user-auth,testing,web"
centos_build_flags = "-Pkube,jupyter-git,remote-user-auth,noSeleniumTest,testing"
if node['build']['test']['community']
centos_build_flags = "-Pcluster -Phops-site -P-web -Ptesting -PnoSeleniumTest"
ubuntu_build_flags = "-Pweb -Pcluster -Phops-site -Ptesting"
end
case node['platform_family']
when "debian"
package ['npm']
npm_package 'bower' do
user 'root'
end
npm_package 'grunt' do
user 'root'
end
npm_package 'bower-npm-resolver' do
user 'root'
end
bash 'root_hack' do
user 'root'
group 'root'
code <<-EOH
echo '{ "allow_root": true }' > /root/.bowerrc
EOH
end
bash 'update-npm' do
user 'root'
group 'root'
code <<-EOH
npm install -g n
n 11.15.0
npm install -g [email protected]
EOH
end
# Build HopsWorks
bash 'build-hopsworks' do
user 'root'
group 'root'
cwd node['test']['hopsworks']['base_dir']
code <<-EOF
cp /home/vagrant/.m2/settings.xml /root/.m2/
mvn clean install #{ubuntu_build_flags} -DskipTests
VERSION=$(mvn -q -Dexec.executable="echo" -Dexec.args='${project.version}' --non-recursive exec:exec)
mv hopsworks-ear/target/hopsworks-ear.ear /tmp/chef-solo/hopsworks-ear\:$VERSION-$VERSION.ear
mv hopsworks-ca/target/hopsworks-ca.war /tmp/chef-solo/hopsworks-ca\:$VERSION-$VERSION.war
mv hopsworks-web/target/hopsworks-web.war /tmp/chef-solo/hopsworks-web\:$VERSION-$VERSION.war
EOF
end
when 'rhel'
remote_file '/tmp/apache-maven-3.6.3-bin.tar.gz' do
source 'https://downloads.apache.org/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz'
owner 'root'
group 'root'
mode '0755'
action :create
end
bash 'extract-maven' do
user 'root'
group 'root'
code <<-EOF
tar xf /tmp/apache-maven-3.6.3-bin.tar.gz -C /opt
ln -s /opt/apache-maven-3.6.3 /opt/maven
EOF
end
bash 'build-hopsworks' do
user 'root'
group 'root'
cwd node['test']['hopsworks']['base_dir']
code <<-EOF
cp /home/vagrant/.m2/settings.xml /root/.m2/
/opt/maven/bin/mvn clean install #{centos_build_flags} -DskipTests
VERSION=$(mvn -q -Dexec.executable="echo" -Dexec.args='${project.version}' --non-recursive exec:exec)
mv hopsworks-ear/target/hopsworks-ear.ear /tmp/chef-solo/hopsworks-ear\:$VERSION-$VERSION.ear
mv hopsworks-ca/target/hopsworks-ca.war /tmp/chef-solo/hopsworks-ca\:$VERSION-$VERSION.war
EOF
end
end
| 27.6 | 107 | 0.661397 |
289c8bd56e92ac7357e9572da8dd146fdf13964e | 380 | cask 'menumeters' do
version :latest
sha256 :no_check
url 'http://www.ragingmenace.com/software/download/MenuMeters.dmg'
name 'MenuMeters'
homepage 'http://www.ragingmenace.com/software/menumeters/'
license :gpl
prefpane 'MenuMeters Installer.app/Contents/Resources/MenuMeters.prefPane'
zap delete: '~/Library/Preferences/com.ragingmenace.MenuMeters.plist'
end
| 27.142857 | 76 | 0.773684 |
bb8796e9a2e78c2cd3b2d5eed2691a63ab82bf5f | 317 | namespace :health do
desc 'Query the healthcheck endpoint'
task check: :environment do
session = ActionDispatch::Integration::Session.new(Rails.application)
session.get(Rails.application.routes.url_helpers.health_path)
puts session.response.body
exit 1 if session.response.server_error?
end
end
| 31.7 | 73 | 0.772871 |
394ec61e0ea014db9f5a5efa22b3a9c7861f01c9 | 1,295 | # encoding: utf-8
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
require 'profiles/latest/personalizer_module_definition'
require 'profiles/latest/modules/personalizer_profile_module'
module Azure::Personalizer::Profiles::Latest
#
# Client class for the Latest profile SDK.
#
class Client < PersonalizerDataClass
include MsRestAzure::Common::Configurable
#
# Initializes a new instance of the Client class.
# @param options [Hash] hash of client options.
# options = {
# tenant_id: 'YOUR TENANT ID',
# client_id: 'YOUR CLIENT ID',
# client_secret: 'YOUR CLIENT SECRET',
# subscription_id: 'YOUR SUBSCRIPTION ID',
# credentials: credentials,
# active_directory_settings: active_directory_settings,
# base_url: 'YOUR BASE URL',
# options: options
# }
# 'credentials' are optional and if not passed in the hash, will be obtained
# from MsRest::TokenCredentials using MsRestAzure::ApplicationTokenProvider.
#
# Also, base_url, active_directory_settings & options are optional.
#
def initialize(options = {})
super(options)
end
end
end
| 33.205128 | 94 | 0.687259 |
ac348ec16cf15628fa6757502f1012669bac3c69 | 2,525 | require "rails_helper"
RSpec.describe "casa_admins/edit", type: :system do
let(:admin) { create :casa_admin }
before { sign_in admin }
context "with valid data" do
it "can successfully edit user email and display name" do
expected_email = "[email protected]"
expected_display_name = "Root Admin"
visit edit_casa_admin_path(admin)
fill_in "Email", with: expected_email
fill_in "Display name", with: expected_display_name
click_on "Submit"
admin.reload
expect(page).to have_text "New admin created successfully"
expect(admin.email).to eq expected_email
expect(admin.display_name).to eq expected_display_name
end
end
context "with invalid data" do
it "shows error message for empty email" do
visit edit_casa_admin_path(admin)
fill_in "Email", with: ""
fill_in "Display name", with: ""
click_on "Submit"
expect(page).to have_text "Email can't be blank"
expect(page).to have_text "Display name can't be blank"
end
end
it "can successfully deactivate", js: true do
another = create(:casa_admin)
visit edit_casa_admin_path(another)
dismiss_confirm do
click_on "Deactivate"
end
expect(page).not_to have_text("Admin was deactivated.")
accept_confirm do
click_on "Deactivate"
end
expect(page).to have_text("Admin was deactivated.")
expect(another.reload.active).to be_falsey
end
it "can resend invitation to a another admin", js: true do
another = create(:casa_admin)
visit edit_casa_admin_path(another)
click_on "Resend Invitation"
expect(page).to have_content("Invitation sent")
deliveries = ActionMailer::Base.deliveries
expect(deliveries.count).to eq(1)
expect(deliveries.last.subject).to have_text "CASA Console invitation instructions"
end
it "can convert the admin to a supervisor", js: true do
another = create(:casa_admin)
visit edit_casa_admin_path(another)
click_on "Change to Supervisor"
expect(page).to have_text("Admin was changed to Supervisor.")
expect(User.find(another.id)).to be_supervisor
end
it "is not able to edit last sign in" do
visit edit_casa_admin_path(admin)
expect(page).to have_text "Added to system "
expect(page).to have_text "Invitation email sent never"
expect(page).to have_text "Last logged in"
expect(page).to have_text "Invitation accepted never"
expect(page).to have_text "Password reset last sent never"
end
end
| 27.150538 | 87 | 0.704158 |
f755678cf8315b3bd32447831e789a8bc0c077af | 2,661 | require 'windows/api'
# This module includes stream I/O, low level I/O, etc.
module Windows
module MSVCRT
module IO
API.auto_namespace = 'Windows::MSVCRT::IO'
API.auto_constant = true
API.auto_method = true
API.auto_unicode = false
private
S_IFMT = 0170000 # file type mask
S_IFDIR = 0040000 # directory
S_IFCHR = 0020000 # character special
S_IFIFO = 0010000 # pipe
S_IFREG = 0100000 # regular
S_IREAD = 0000400 # read permission, owner
S_IWRITE = 0000200 # write permission, owner
S_IEXEC = 0000100 # execute/search permission, owner
SH_DENYNO = 0x40 # deny none mode
SHORT_LIVED = 0x1000 # temporary file storage
API.new('clearerr', 'I', 'V', MSVCRT_DLL)
API.new('_close', 'I', 'V', MSVCRT_DLL)
API.new('fclose', 'I', 'I', MSVCRT_DLL)
API.new('_fcloseall', 'V', 'I', MSVCRT_DLL)
API.new('_fdopen', 'IP', 'I', MSVCRT_DLL)
API.new('feof', 'I', 'I', MSVCRT_DLL)
API.new('ferror', 'L', 'I', MSVCRT_DLL)
API.new('fflush', 'I', 'I', MSVCRT_DLL)
API.new('fgetc', 'L', 'I', MSVCRT_DLL)
API.new('fgetpos', 'LP', 'I', MSVCRT_DLL)
API.new('fgetwc', 'L', 'I', MSVCRT_DLL)
API.new('fgets', 'PIL', 'P', MSVCRT_DLL)
API.new('fgetws', 'PIL', 'P', MSVCRT_DLL)
API.new('_fileno', 'I', 'I', MSVCRT_DLL)
API.new('_flushall', 'V', 'I', MSVCRT_DLL)
API.new('fopen', 'PP', 'I', MSVCRT_DLL)
API.new('fputs', 'PL', 'I', MSVCRT_DLL)
API.new('fputws', 'PL', 'I', MSVCRT_DLL)
API.new('getc', 'L', 'I', MSVCRT_DLL)
API.new('getwc', 'L', 'L', MSVCRT_DLL)
API.new('_open', 'PII', 'I', MSVCRT_DLL)
API.new('_rmtmp', 'V', 'I', MSVCRT_DLL)
API.new('_setmode', 'II', 'I', MSVCRT_DLL)
API.new('_sopen', 'PIII', 'I', MSVCRT_DLL)
API.new('_tempnam', 'PP', 'P', MSVCRT_DLL)
API.new('tmpfile', 'V', 'L', MSVCRT_DLL)
API.new('tmpnam', 'P', 'P', MSVCRT_DLL)
# Wide character versions
API.new('_wopen', 'PII', 'I', MSVCRT_DLL)
API.new('_wfdopen', 'IP', 'I', MSVCRT_DLL)
API.new('_wfopen', 'PPI', 'I', MSVCRT_DLL)
API.new('_wsopen', 'PIII', 'I', MSVCRT_DLL)
API.new('_wtempnam', 'PP', 'P', MSVCRT_DLL)
API.new('_wtmpnam', 'P', 'P', MSVCRT_DLL)
# VC++ 8.0 or later
begin
API.new('_sopen_s', 'PPIII', 'L', MSVCRT_DLL)
API.new('_tmpfile_s', 'P', 'L', MSVCRT_DLL)
API.new('_wsopen_s', 'PPIII', 'L', MSVCRT_DLL)
rescue Win32::API::LoadLibraryError
# Ignore - you must check for it via 'defined?'
end
end
end
end
| 35.959459 | 59 | 0.56708 |
f7b6bf526a021290c5475a82d2b27708497e2fde | 5,325 | # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
require 'date'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# Result of a query request for a list of domains. Contains DomainSummary items.
class TenantManagerControlPlane::Models::DomainCollection
# **[Required]** Array containing DomainSummary items.
# @return [Array<OCI::TenantManagerControlPlane::Models::DomainSummary>]
attr_accessor :items
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
# rubocop:disable Style/SymbolLiteral
'items': :'items'
# rubocop:enable Style/SymbolLiteral
}
end
# Attribute type mapping.
def self.swagger_types
{
# rubocop:disable Style/SymbolLiteral
'items': :'Array<OCI::TenantManagerControlPlane::Models::DomainSummary>'
# rubocop:enable Style/SymbolLiteral
}
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
# @option attributes [Array<OCI::TenantManagerControlPlane::Models::DomainSummary>] :items The value to assign to the {#items} property
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
self.items = attributes[:'items'] if attributes[:'items']
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# Checks equality by comparing each attribute.
# @param [Object] other the other object to be compared
def ==(other)
return true if equal?(other)
self.class == other.class &&
items == other.items
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# @see the `==` method
# @param [Object] other the other object to be compared
def eql?(other)
self == other
end
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[items].hash
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
public_method("#{key}=").call(
attributes[self.class.attribute_map[key]]
.map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) }
)
end
elsif !attributes[self.class.attribute_map[key]].nil?
public_method("#{key}=").call(
OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]])
)
end
# or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = public_method(attr).call
next if value.nil? && !instance_variable_defined?("@#{attr}")
hash[param] = _to_hash(value)
end
hash
end
private
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
# rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
| 35.264901 | 245 | 0.674178 |
1a421a7cc1d845c25b4d424343930ff85e64b5dc | 838 | #!/usr/bin/env ruby
# encoding: utf-8
# File: monitor_qt.rb
# Created: 17/08/13
#
# (c) Michel Demazure <[email protected]>
require_relative('version.rb')
require_relative('elements/monitor_help.rb')
require_relative 'elements/monitor_elements.rb'
require_relative('elements/monitor_central_widget.rb')
module JacintheManagement
# put REAL=false to avoid automatic processing of sales
REAL = true
end
JacintheManagement.open_log('monitor.log')
JacintheManagement.log('Opening monitor')
JacintheManagement::Core::Infos.report.each do |info|
JacintheManagement.log(info)
end
central_class = JacintheManagement::GuiQt::MonitorCentralWidget
JacintheManagement::GuiQt::CommonMain.run(central_class)
JacintheManagement::Core::Infos.report.each do |info|
JacintheManagement.log(info)
end
JacintheManagement.log('Closing monitor')
| 27.933333 | 63 | 0.801909 |
b94a34f690a52449f2e7e9446db1a3f3172cf7d1 | 694 | class CdsImporter
class EntityMapper
class GeographicalAreaDescriptionPeriodMapper < BaseMapper
self.entity_class = 'GeographicalAreaDescriptionPeriod'.freeze
self.mapping_root = 'GeographicalArea'.freeze
self.mapping_path = 'geographicalAreaDescriptionPeriod'.freeze
self.entity_mapping = base_mapping.merge(
"#{mapping_path}.sid" => :geographical_area_description_period_sid,
'sid' => :geographical_area_sid,
'geographicalAreaId' => :geographical_area_id
).freeze
self.entity_mapping_key_as_array = mapping_with_key_as_array.freeze
self.entity_mapping_keys_to_parse = mapping_keys_to_parse.freeze
end
end
end
| 31.545455 | 75 | 0.753602 |
33625f276ed201937045a1414eb1fde0d8c72969 | 1,620 | # Puma can serve each request in a thread from an internal thread pool.
# The `threads` method setting takes two numbers: a minimum and maximum.
# Any libraries that use thread pools should be configured to match
# the maximum value specified for Puma. Default is set to 5 threads for minimum
# and maximum; this matches the default thread size of Active Record.
#
max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }
min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count }
threads min_threads_count, max_threads_count
# Specifies the `port` that Puma will listen on to receive requests; default is 3000.
#
port ENV.fetch("PORT") { 3000 }
# Specifies the `environment` that Puma will run in.
#
environment ENV.fetch("RAILS_ENV") { "development" }
# Specifies the `pidfile` that Puma will use.
pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" }
# Specifies the number of `workers` to boot in clustered mode.
# Workers are forked web server processes. If using threads and workers together
# the concurrency of the application would be max `threads` * `workers`.
# Workers do not work on JRuby or Windows (both of which do not support
# processes).
#
# workers ENV.fetch("WEB_CONCURRENCY") { 2 }
# Use the `preload_app!` method when specifying a `workers` number.
# This directive tells Puma to first boot the application and load code
# before forking the application. This takes advantage of Copy On Write
# process behavior so workers use less memory.
#
# preload_app!
# Allow puma to be restarted by `rails restart` command.
plugin :tmp_restart
activate_control_app
plugin :yabeda | 40.5 | 85 | 0.762346 |
7a659e13818f6a448ec98becd0c18bbc85f85939 | 136 | class RemoveInstitutionsFromNodes < ActiveRecord::Migration[4.2]
def change
remove_column :nodes, :institutions, :array
end
end
| 22.666667 | 64 | 0.772059 |
289f9c5553769285077d11ec05263c73d29b7bc7 | 4,726 | #!/usr/bin/env ruby
require 'mux_ruby'
require 'solid_assert'
SolidAssert.enable_assertions
# Authentication Setup
openapi = MuxRuby.configure do |config|
config.username = ENV['MUX_TOKEN_ID']
config.password = ENV['MUX_TOKEN_SECRET']
end
# API Client Initialization
assets_api = MuxRuby::AssetsApi.new
# ========== create-asset ==========
car = MuxRuby::CreateAssetRequest.new
car.input = [{:url => 'https://storage.googleapis.com/muxdemofiles/mux-video-intro.mp4'}, {:url => "https://tears-of-steel-subtitles.s3.amazonaws.com/tears-fr.vtt", :type => "text", :text_type => "subtitles", :name => "French", :language_code => "fr", :closed_captions => false}]
create_response = assets_api.create_asset(car)
assert create_response != nil
assert create_response.data.id != nil
puts "create-asset OK ✅"
# ========== list-assets ==========
assets = assets_api.list_assets()
assert assets != nil
assert assets.data.first.id == create_response.data.id
puts "list-assets OK ✅"
# Wait for the asset to become ready...
if create_response.data.status != 'ready'
puts " waiting for asset to become ready..."
while true do
# ========== get-asset ==========
asset = assets_api.get_asset(create_response.data.id)
assert asset != nil
assert asset.data.id == create_response.data.id
if asset.data.status != 'ready'
puts "Asset not ready yet, sleeping..."
sleep(1)
else
puts "Asset ready checking input info."
# ========== get-asset-input-info ==========
input_info = assets_api.get_asset_input_info(asset.data.id)
assert input_info != nil
assert input_info.data != nil
break
end
end
end
puts "get-asset OK ✅"
puts "get-asset-input-info OK ✅"
# ========== create-asset-playback-id ==========
cpbr = MuxRuby::CreatePlaybackIDRequest.new
cpbr.policy = MuxRuby::PlaybackPolicy::PUBLIC
pb_id_c = assets_api.create_asset_playback_id(create_response.data.id, cpbr)
assert pb_id_c != nil
assert pb_id_c.data != nil
puts "create-asset-playback-id OK ✅"
# ========== get-asset-playback-id ==========
pb_id = assets_api.get_asset_playback_id(create_response.data.id, pb_id_c.data.id)
assert pb_id != nil
assert pb_id.data != nil
assert pb_id.data.id == pb_id_c.data.id
puts "get-asset-playback-id OK ✅"
# ========== update-asset-mp4-support ==========
mp4_req = MuxRuby::UpdateAssetMP4SupportRequest.new
mp4_req.mp4_support = 'standard'
mp4_asset = assets_api.update_asset_mp4_support(create_response.data.id, mp4_req)
assert mp4_asset != nil
assert mp4_asset.data != nil
assert mp4_asset.data.id == create_response.data.id
assert mp4_asset.data.mp4_support == 'standard'
puts "update-asset-mp4-support OK ✅"
# ========== update-asset-master-access ==========
master_req = MuxRuby::UpdateAssetMasterAccessRequest.new
master_req.master_access = 'temporary'
master_asset = assets_api.update_asset_master_access(create_response.data.id, master_req)
assert master_asset != nil
assert master_asset.data != nil
assert master_asset.data.id == create_response.data.id
assert master_asset.data.master_access == 'temporary'
puts "update-asset-master-access OK ✅"
# ========== create-asset-track ==========
cat = MuxRuby::CreateTrackRequest.new(:url => "https://tears-of-steel-subtitles.s3.amazonaws.com/tears-en.vtt", :type => "text", :text_type => "subtitles", :language_code => "en", :name => "English", :closed_captions => false)
subtitles_track = assets_api.create_asset_track(create_response.data.id, cat)
assert subtitles_track != nil
assert subtitles_track.data.id != nil
assert subtitles_track.data.name == 'English'
asset_with_2_captions = assets_api.get_asset(create_response.data.id)
assert asset_with_2_captions.data.tracks.length == 4 # Audio, Video, French that we ingested with the asset, and the English we added here!
puts "create-asset-track OK ✅"
# ========== delete-asset-track ==========
assets_api.delete_asset_track(create_response.data.id, subtitles_track.data.id)
asset_with_1_captions = assets_api.get_asset(create_response.data.id)
assert asset_with_1_captions.data.tracks.length == 3 # Audio, Video, French that we ingested with the asset
puts "delete-asset-track OK ✅"
# ========== delete-asset-playback-id ==========
assets_api.delete_asset_playback_id(create_response.data.id, pb_id_c.data.id)
deleted_playback_id_asset = assets_api.get_asset(create_response.data.id)
assert deleted_playback_id_asset.data.playback_ids == nil
puts "delete-asset-playback-id OK ✅"
# ========== delete-asset ==========
assets_api.delete_asset(create_response.data.id)
begin
assets_api.get_asset(create_response.data.id)
puts 'Should have errored here.'
exit 255
rescue MuxRuby::NotFoundError => e
assert e != nil
end
puts "delete-asset OK ✅" | 39.057851 | 279 | 0.720906 |
79e639b5088a690b1533920aa02dbea907f25269 | 14,904 | # encoding: utf-8
require 'securerandom'
require 'abstract_unit'
require 'active_support/core_ext/string/inflections'
require 'active_support/json'
class TestJSONEncoding < ActiveSupport::TestCase
class Foo
def initialize(a, b)
@a, @b = a, b
end
end
class Hashlike
def to_hash
{ :foo => "hello", :bar => "world" }
end
end
class Custom
def initialize(serialized)
@serialized = serialized
end
def as_json(options = nil)
@serialized
end
end
class CustomWithOptions
attr_accessor :foo, :bar
def as_json(options={})
options[:only] = %w(foo bar)
super(options)
end
end
class OptionsTest
def as_json(options = :default)
options
end
end
class HashWithAsJson < Hash
attr_accessor :as_json_called
def initialize(*)
super
end
def as_json(options={})
@as_json_called = true
super
end
end
TrueTests = [[ true, %(true) ]]
FalseTests = [[ false, %(false) ]]
NilTests = [[ nil, %(null) ]]
NumericTests = [[ 1, %(1) ],
[ 2.5, %(2.5) ],
[ 0.0/0.0, %(null) ],
[ 1.0/0.0, %(null) ],
[ -1.0/0.0, %(null) ],
[ BigDecimal('0.0')/BigDecimal('0.0'), %(null) ],
[ BigDecimal('2.5'), %("#{BigDecimal('2.5').to_s}") ]]
StringTests = [[ 'this is the <string>', %("this is the \\u003cstring\\u003e")],
[ 'a "string" with quotes & an ampersand', %("a \\"string\\" with quotes \\u0026 an ampersand") ],
[ 'http://test.host/posts/1', %("http://test.host/posts/1")],
[ "Control characters: \x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\u2028\u2029",
%("Control characters: \\u0000\\u0001\\u0002\\u0003\\u0004\\u0005\\u0006\\u0007\\b\\t\\n\\u000b\\f\\r\\u000e\\u000f\\u0010\\u0011\\u0012\\u0013\\u0014\\u0015\\u0016\\u0017\\u0018\\u0019\\u001a\\u001b\\u001c\\u001d\\u001e\\u001f\\u2028\\u2029") ]]
ArrayTests = [[ ['a', 'b', 'c'], %([\"a\",\"b\",\"c\"]) ],
[ [1, 'a', :b, nil, false], %([1,\"a\",\"b\",null,false]) ]]
RangeTests = [[ 1..2, %("1..2")],
[ 1...2, %("1...2")],
[ 1.5..2.5, %("1.5..2.5")]]
SymbolTests = [[ :a, %("a") ],
[ :this, %("this") ],
[ :"a b", %("a b") ]]
ObjectTests = [[ Foo.new(1, 2), %({\"a\":1,\"b\":2}) ]]
HashlikeTests = [[ Hashlike.new, %({\"bar\":\"world\",\"foo\":\"hello\"}) ]]
CustomTests = [[ Custom.new("custom"), '"custom"' ],
[ Custom.new(nil), 'null' ],
[ Custom.new(:a), '"a"' ],
[ Custom.new([ :foo, "bar" ]), '["foo","bar"]' ],
[ Custom.new({ :foo => "hello", :bar => "world" }), '{"bar":"world","foo":"hello"}' ],
[ Custom.new(Hashlike.new), '{"bar":"world","foo":"hello"}' ],
[ Custom.new(Custom.new(Custom.new(:a))), '"a"' ]]
RegexpTests = [[ /^a/, '"(?-mix:^a)"' ], [/^\w{1,2}[a-z]+/ix, '"(?ix-m:^\\\\w{1,2}[a-z]+)"']]
DateTests = [[ Date.new(2005,2,1), %("2005/02/01") ]]
TimeTests = [[ Time.utc(2005,2,1,15,15,10), %("2005/02/01 15:15:10 +0000") ]]
DateTimeTests = [[ DateTime.civil(2005,2,1,15,15,10), %("2005/02/01 15:15:10 +0000") ]]
StandardDateTests = [[ Date.new(2005,2,1), %("2005-02-01") ]]
StandardTimeTests = [[ Time.utc(2005,2,1,15,15,10), %("2005-02-01T15:15:10.000Z") ]]
StandardDateTimeTests = [[ DateTime.civil(2005,2,1,15,15,10), %("2005-02-01T15:15:10.000+00:00") ]]
StandardStringTests = [[ 'this is the <string>', %("this is the <string>")]]
def sorted_json(json)
return json unless json =~ /^\{.*\}$/
'{' + json[1..-2].split(',').sort.join(',') + '}'
end
constants.grep(/Tests$/).each do |class_tests|
define_method("test_#{class_tests[0..-6].underscore}") do
begin
prev = ActiveSupport.use_standard_json_time_format
ActiveSupport.escape_html_entities_in_json = class_tests !~ /^Standard/
ActiveSupport.use_standard_json_time_format = class_tests =~ /^Standard/
self.class.const_get(class_tests).each do |pair|
assert_equal pair.last, sorted_json(ActiveSupport::JSON.encode(pair.first))
end
ensure
ActiveSupport.escape_html_entities_in_json = false
ActiveSupport.use_standard_json_time_format = prev
end
end
end
def test_process_status
# There doesn't seem to be a good way to get a handle on a Process::Status object without actually
# creating a child process, hence this to populate $?
system("not_a_real_program_#{SecureRandom.hex}")
assert_equal %({"exitstatus":#{$?.exitstatus},"pid":#{$?.pid}}), ActiveSupport::JSON.encode($?)
end
def test_hash_encoding
assert_equal %({\"a\":\"b\"}), ActiveSupport::JSON.encode(:a => :b)
assert_equal %({\"a\":1}), ActiveSupport::JSON.encode('a' => 1)
assert_equal %({\"a\":[1,2]}), ActiveSupport::JSON.encode('a' => [1,2])
assert_equal %({"1":2}), ActiveSupport::JSON.encode(1 => 2)
assert_equal %({\"a\":\"b\",\"c\":\"d\"}), sorted_json(ActiveSupport::JSON.encode(:a => :b, :c => :d))
end
def test_utf8_string_encoded_properly
result = ActiveSupport::JSON.encode('€2.99')
assert_equal '"€2.99"', result
assert_equal(Encoding::UTF_8, result.encoding)
result = ActiveSupport::JSON.encode('✎☺')
assert_equal '"✎☺"', result
assert_equal(Encoding::UTF_8, result.encoding)
end
def test_non_utf8_string_transcodes
s = '二'.encode('Shift_JIS')
result = ActiveSupport::JSON.encode(s)
assert_equal '"二"', result
assert_equal Encoding::UTF_8, result.encoding
end
def test_wide_utf8_chars
w = '𠜎'
result = ActiveSupport::JSON.encode(w)
assert_equal '"𠜎"', result
end
def test_wide_utf8_roundtrip
hash = { string: "𐒑" }
json = ActiveSupport::JSON.encode(hash)
decoded_hash = ActiveSupport::JSON.decode(json)
assert_equal "𐒑", decoded_hash['string']
end
def test_exception_raised_when_encoding_circular_reference_in_array
a = [1]
a << a
assert_deprecated do
assert_raise(ActiveSupport::JSON::Encoding::CircularReferenceError) { ActiveSupport::JSON.encode(a) }
end
end
def test_exception_raised_when_encoding_circular_reference_in_hash
a = { :name => 'foo' }
a[:next] = a
assert_deprecated do
assert_raise(ActiveSupport::JSON::Encoding::CircularReferenceError) { ActiveSupport::JSON.encode(a) }
end
end
def test_exception_raised_when_encoding_circular_reference_in_hash_inside_array
a = { :name => 'foo', :sub => [] }
a[:sub] << a
assert_deprecated do
assert_raise(ActiveSupport::JSON::Encoding::CircularReferenceError) { ActiveSupport::JSON.encode(a) }
end
end
def test_hash_key_identifiers_are_always_quoted
values = {0 => 0, 1 => 1, :_ => :_, "$" => "$", "a" => "a", :A => :A, :A0 => :A0, "A0B" => "A0B"}
assert_equal %w( "$" "A" "A0" "A0B" "_" "a" "0" "1" ).sort, object_keys(ActiveSupport::JSON.encode(values))
end
def test_hash_should_allow_key_filtering_with_only
assert_equal %({"a":1}), ActiveSupport::JSON.encode({'a' => 1, :b => 2, :c => 3}, :only => 'a')
end
def test_hash_should_allow_key_filtering_with_except
assert_equal %({"b":2}), ActiveSupport::JSON.encode({'foo' => 'bar', :b => 2, :c => 3}, :except => ['foo', :c])
end
def test_time_to_json_includes_local_offset
prev = ActiveSupport.use_standard_json_time_format
ActiveSupport.use_standard_json_time_format = true
with_env_tz 'US/Eastern' do
assert_equal %("2005-02-01T15:15:10.000-05:00"), ActiveSupport::JSON.encode(Time.local(2005,2,1,15,15,10))
end
ensure
ActiveSupport.use_standard_json_time_format = prev
end
def test_hash_with_time_to_json
prev = ActiveSupport.use_standard_json_time_format
ActiveSupport.use_standard_json_time_format = false
assert_equal '{"time":"2009/01/01 00:00:00 +0000"}', { :time => Time.utc(2009) }.to_json
ensure
ActiveSupport.use_standard_json_time_format = prev
end
def test_nested_hash_with_float
assert_nothing_raised do
hash = {
"CHI" => {
:display_name => "chicago",
:latitude => 123.234
}
}
ActiveSupport::JSON.encode(hash)
end
end
def test_hash_like_with_options
h = Hashlike.new
json = h.to_json :only => [:foo]
assert_equal({"foo"=>"hello"}, JSON.parse(json))
end
def test_object_to_json_with_options
obj = Object.new
obj.instance_variable_set :@foo, "hello"
obj.instance_variable_set :@bar, "world"
json = obj.to_json :only => ["foo"]
assert_equal({"foo"=>"hello"}, JSON.parse(json))
end
def test_struct_to_json_with_options
struct = Struct.new(:foo, :bar).new
struct.foo = "hello"
struct.bar = "world"
json = struct.to_json :only => [:foo]
assert_equal({"foo"=>"hello"}, JSON.parse(json))
end
def test_hash_should_pass_encoding_options_to_children_in_as_json
person = {
:name => 'John',
:address => {
:city => 'London',
:country => 'UK'
}
}
json = person.as_json :only => [:address, :city]
assert_equal({ 'address' => { 'city' => 'London' }}, json)
end
def test_hash_should_pass_encoding_options_to_children_in_to_json
person = {
:name => 'John',
:address => {
:city => 'London',
:country => 'UK'
}
}
json = person.to_json :only => [:address, :city]
assert_equal(%({"address":{"city":"London"}}), json)
end
def test_array_should_pass_encoding_options_to_children_in_as_json
people = [
{ :name => 'John', :address => { :city => 'London', :country => 'UK' }},
{ :name => 'Jean', :address => { :city => 'Paris' , :country => 'France' }}
]
json = people.as_json :only => [:address, :city]
expected = [
{ 'address' => { 'city' => 'London' }},
{ 'address' => { 'city' => 'Paris' }}
]
assert_equal(expected, json)
end
def test_array_should_pass_encoding_options_to_children_in_to_json
people = [
{ :name => 'John', :address => { :city => 'London', :country => 'UK' }},
{ :name => 'Jean', :address => { :city => 'Paris' , :country => 'France' }}
]
json = people.to_json :only => [:address, :city]
assert_equal(%([{"address":{"city":"London"}},{"address":{"city":"Paris"}}]), json)
end
def test_enumerable_should_pass_encoding_options_to_children_in_as_json
people = [
{ :name => 'John', :address => { :city => 'London', :country => 'UK' }},
{ :name => 'Jean', :address => { :city => 'Paris' , :country => 'France' }}
]
json = people.each.as_json :only => [:address, :city]
expected = [
{ 'address' => { 'city' => 'London' }},
{ 'address' => { 'city' => 'Paris' }}
]
assert_equal(expected, json)
end
def test_enumerable_should_pass_encoding_options_to_children_in_to_json
people = [
{ :name => 'John', :address => { :city => 'London', :country => 'UK' }},
{ :name => 'Jean', :address => { :city => 'Paris' , :country => 'France' }}
]
json = people.each.to_json :only => [:address, :city]
assert_equal(%([{"address":{"city":"London"}},{"address":{"city":"Paris"}}]), json)
end
def test_hash_to_json_should_not_keep_options_around
f = CustomWithOptions.new
f.foo = "hello"
f.bar = "world"
hash = {"foo" => f, "other_hash" => {"foo" => "other_foo", "test" => "other_test"}}
assert_equal({"foo"=>{"foo"=>"hello","bar"=>"world"},
"other_hash" => {"foo"=>"other_foo","test"=>"other_test"}}, ActiveSupport::JSON.decode(hash.to_json))
end
def test_array_to_json_should_not_keep_options_around
f = CustomWithOptions.new
f.foo = "hello"
f.bar = "world"
array = [f, {"foo" => "other_foo", "test" => "other_test"}]
assert_equal([{"foo"=>"hello","bar"=>"world"},
{"foo"=>"other_foo","test"=>"other_test"}], ActiveSupport::JSON.decode(array.to_json))
end
def test_hash_as_json_without_options
json = { foo: OptionsTest.new }.as_json
assert_equal({"foo" => :default}, json)
end
def test_array_as_json_without_options
json = [ OptionsTest.new ].as_json
assert_equal([:default], json)
end
def test_struct_encoding
Struct.new('UserNameAndEmail', :name, :email)
Struct.new('UserNameAndDate', :name, :date)
Struct.new('Custom', :name, :sub)
user_email = Struct::UserNameAndEmail.new 'David', '[email protected]'
user_birthday = Struct::UserNameAndDate.new 'David', Date.new(2010, 01, 01)
custom = Struct::Custom.new 'David', user_birthday
json_strings = ""
json_string_and_date = ""
json_custom = ""
assert_nothing_raised do
json_strings = user_email.to_json
json_string_and_date = user_birthday.to_json
json_custom = custom.to_json
end
assert_equal({"name" => "David",
"sub" => {
"name" => "David",
"date" => "2010-01-01" }}, ActiveSupport::JSON.decode(json_custom))
assert_equal({"name" => "David", "email" => "[email protected]"},
ActiveSupport::JSON.decode(json_strings))
assert_equal({"name" => "David", "date" => "2010-01-01"},
ActiveSupport::JSON.decode(json_string_and_date))
end
def test_nil_true_and_false_represented_as_themselves
assert_equal nil, nil.as_json
assert_equal true, true.as_json
assert_equal false, false.as_json
end
def test_json_gem_dump_by_passing_active_support_encoder
h = HashWithAsJson.new
h[:foo] = "hello"
h[:bar] = "world"
assert_equal %({"foo":"hello","bar":"world"}), JSON.dump(h)
assert_nil h.as_json_called
end
def test_json_gem_generate_by_passing_active_support_encoder
h = HashWithAsJson.new
h[:foo] = "hello"
h[:bar] = "world"
assert_equal %({"foo":"hello","bar":"world"}), JSON.generate(h)
assert_nil h.as_json_called
end
def test_json_gem_pretty_generate_by_passing_active_support_encoder
h = HashWithAsJson.new
h[:foo] = "hello"
h[:bar] = "world"
assert_equal <<EXPECTED.chomp, JSON.pretty_generate(h)
{
"foo": "hello",
"bar": "world"
}
EXPECTED
assert_nil h.as_json_called
end
protected
def object_keys(json_object)
json_object[1..-2].scan(/([^{}:,\s]+):/).flatten.sort
end
def with_env_tz(new_tz = 'US/Eastern')
old_tz, ENV['TZ'] = ENV['TZ'], new_tz
yield
ensure
old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
end
end
| 32.900662 | 267 | 0.595142 |
7aba78ecb0771c46ff28f8125a83df922e35e9ca | 693 | name "nghttp2"
default_version "1.12.0"
dependency "openssl"
source :url => "https://github.com/nghttp2/nghttp2/releases/download/v1.12.0/nghttp2-#{version}.tar.gz",
:md5 => "04235f1d7170a2efce535068319180a1"
relative_path "nghttp2-#{version}"
env = {
"OPENSSL_CFLAGS" => "-I#{install_dir}/embedded/include/openssl",
"OPENSSL_LIBS" => "-L#{install_dir}/embedded/lib"
}
build do
command [
"./configure",
"--disable-app",
"--disable-examples",
"--disable-hpack-tools",
"--prefix=#{install_dir}/embedded",
""
].join(" "), :env => env
command "make -j #{workers}", :env => {"LD_RUN_PATH" => "#{install_dir}/embedded/lib"}
command "make install"
end
| 24.75 | 104 | 0.646465 |
aca099d3abbc3168e45c2023f69ee9657607d0ec | 1,061 | require_relative 'lib/ip_info/version'
Gem::Specification.new do |spec|
spec.name = "ip_info"
spec.version = IpInfo::VERSION
spec.authors = ["Andersen Fan"]
spec.email = ["[email protected]"]
spec.summary = %q{IP info}
spec.description = %q{country, city, location, postal}
spec.homepage = "https://github.com/as181920/ip_info"
spec.license = "MIT"
spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
spec.metadata["allowed_push_host"] = ""
spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = "https://github.com/as181920/ip_info"
spec.metadata["changelog_uri"] = "https://github.com/as181920/ip_info"
spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency "maxmind-geoip2"
end
| 36.586207 | 85 | 0.644675 |
ed74cca95c8bd3f98f9a9f53ab342f5b2a8efb86 | 872 | require "domain/customers/validations/on_create"
require "spec/domain/shared/shared_examples"
RSpec.describe Carpanta::Domain::Customers::Validations::OnCreate do
describe "#call" do
subject { described_class.new }
let(:default_params) do
{
name: "Donald",
surname: "Duck",
email: "[email protected]"
}
end
it_behaves_like "successful"
context "invalid" do
context "name" do
it_behaves_like "must be a string", {name: 123}, :name
end
context "surname" do
it_behaves_like "must be a string", {surname: 123}, :surname
end
context "email" do
it_behaves_like "is in invalid format", {email: "donald.duck@carpanta"}, :email
end
context "phone" do
it_behaves_like "must be a string", {phone: 123}, :phone
end
end
end
end
| 24.222222 | 87 | 0.629587 |
f8b8a33a9c00ad09e9434b2329f6aa1223edeb8e | 1,153 | # Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
#
# Note: You can only move either down or right at any point in time.
#
# Example 1:
# [[1,3,1],
# [1,5,1],
# [4,2,1]]
# Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.
# @param {Integer[][]} grid
# @return {Integer}
def min_path_sum(grid)
sums = min_path_sum_helper(grid)
sums.last.last
end
# dp bottom-up
def min_path_sum_helper(grid)
rows = grid.size
cols = grid.first.size
sums = Array.new(rows) { Array.new(cols) { 0 } }
sums[0][0] = grid[0][0]
# fill the costs for moving thru first row (right)
# & moving thru col (down)
(1...rows).each do |i|
sums[i][0] = sums[i - 1][0] + grid[i][0]
end
(1...cols).each do |j|
sums[0][j] = sums[0][j - 1] + grid[0][j]
end
# now when filling costs we can pick the min
# between the value from either direction
(1...rows).each do |i|
(1...cols).each do |j|
min_dir = [sums[i][j - 1], sums[i - 1][j]].min
sums[i][j] = min_dir + grid[i][j]
end
end
sums
end
| 24.531915 | 151 | 0.619254 |
187e22e0583dd27b87206e6b78c140cd04ffa427 | 834 | module Bosh::Director
module CpiConfig
class Cpi
extend ValidationHelper
attr_reader :name, :type, :properties
def initialize(name, type, exec_path, properties)
@name = name
@type = type
@exec_path = exec_path
@properties = properties
end
def self.parse(cpi_hash)
name = safe_property(cpi_hash, 'name', :class => String)
type = safe_property(cpi_hash, 'type', :class => String)
exec_path = safe_property(cpi_hash, 'exec_path', :class => String, :optional => true)
properties = safe_property(cpi_hash, 'properties', :class => Hash, :optional => true, :default => {})
new(name, type, exec_path, properties)
end
def exec_path
@exec_path || "/var/vcap/jobs/#{type}_cpi/bin/cpi"
end
end
end
end
| 28.758621 | 109 | 0.61271 |
1c25c5daad7f27c1ed39174091bdf4b3fe8da98b | 9,851 | #
# Author:: Tyler Cloke ([email protected])
# Copyright:: Copyright 2015-2016, Chef Software, Inc
# License:: Apache License, Version 2.0
#
# 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 "chef/json_compat"
require "chef/mixin/params_validate"
require "chef/exceptions"
require "chef/server_api"
class Chef
# Class for interacting with a chef key object. Can be used to create new keys,
# save to server, load keys from server, list keys, delete keys, etc.
#
# @author Tyler Cloke
#
# @attr [String] actor the name of the client or user that this key is for
# @attr [String] name the name of the key
# @attr [String] public_key the RSA string of this key
# @attr [String] private_key the RSA string of the private key if returned via a POST or PUT
# @attr [String] expiration_date the ISO formatted string YYYY-MM-DDTHH:MM:SSZ, i.e. 2020-12-24T21:00:00Z
# @attr [String] rest Chef::ServerAPI object, initialized and cached via chef_rest method
# @attr [string] api_base either "users" or "clients", initialized and cached via api_base method
#
# @attr_reader [String] actor_field_name must be either 'client' or 'user'
class Key
include Chef::Mixin::ParamsValidate
attr_reader :actor_field_name
def initialize(actor, actor_field_name)
# Actor that the key is for, either a client or a user.
@actor = actor
unless actor_field_name == "user" || actor_field_name == "client"
raise Chef::Exceptions::InvalidKeyArgument, "the second argument to initialize must be either 'user' or 'client'"
end
@actor_field_name = actor_field_name
@name = nil
@public_key = nil
@private_key = nil
@expiration_date = nil
@create_key = nil
end
def chef_rest
@rest ||= if @actor_field_name == "user"
Chef::ServerAPI.new(Chef::Config[:chef_server_root])
else
Chef::ServerAPI.new(Chef::Config[:chef_server_url])
end
end
def api_base
@api_base ||= if @actor_field_name == "user"
"users"
else
"clients"
end
end
def actor(arg = nil)
set_or_return(:actor, arg,
:regex => /^[a-z0-9\-_]+$/)
end
def name(arg = nil)
set_or_return(:name, arg,
:kind_of => String)
end
def public_key(arg = nil)
raise Chef::Exceptions::InvalidKeyAttribute, "you cannot set the public_key if create_key is true" if !arg.nil? && @create_key
set_or_return(:public_key, arg,
:kind_of => String)
end
def private_key(arg = nil)
set_or_return(:private_key, arg,
:kind_of => String)
end
def delete_public_key
@public_key = nil
end
def delete_create_key
@create_key = nil
end
def create_key(arg = nil)
raise Chef::Exceptions::InvalidKeyAttribute, "you cannot set create_key to true if the public_key field exists" if arg == true && !@public_key.nil?
set_or_return(:create_key, arg,
:kind_of => [TrueClass, FalseClass])
end
def expiration_date(arg = nil)
set_or_return(:expiration_date, arg,
:regex => /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z|infinity)$/)
end
def to_hash
result = {
@actor_field_name => @actor,
}
result["name"] = @name if @name
result["public_key"] = @public_key if @public_key
result["private_key"] = @private_key if @private_key
result["expiration_date"] = @expiration_date if @expiration_date
result["create_key"] = @create_key if @create_key
result
end
def to_json(*a)
Chef::JSONCompat.to_json(to_hash, *a)
end
def create
# if public_key is undefined and create_key is false, we cannot create
if @public_key.nil? && !@create_key
raise Chef::Exceptions::MissingKeyAttribute, "either public_key must be defined or create_key must be true"
end
# defaults the key name to the fingerprint of the key
if @name.nil?
# if they didn't pass a public_key,
#then they must supply a name because we can't generate a fingerprint
unless @public_key.nil?
@name = fingerprint
else
raise Chef::Exceptions::MissingKeyAttribute, "a name cannot be auto-generated if no public key passed, either pass a public key or supply a name"
end
end
payload = { "name" => @name }
payload["public_key"] = @public_key unless @public_key.nil?
payload["create_key"] = @create_key if @create_key
payload["expiration_date"] = @expiration_date unless @expiration_date.nil?
result = chef_rest.post("#{api_base}/#{@actor}/keys", payload)
# append the private key to the current key if the server returned one,
# since the POST endpoint just returns uri and private_key if needed.
new_key = self.to_hash
new_key["private_key"] = result["private_key"] if result["private_key"]
Chef::Key.from_hash(new_key)
end
def fingerprint
self.class.generate_fingerprint(@public_key)
end
# set @name and pass put_name if you wish to update the name of an existing key put_name to @name
def update(put_name = nil)
if @name.nil? && put_name.nil?
raise Chef::Exceptions::MissingKeyAttribute, "the name field must be populated or you must pass a name to update when update is called"
end
# If no name was passed, fall back to using @name in the PUT URL, otherwise
# use the put_name passed. This will update the a key by the name put_name
# to @name.
put_name = @name if put_name.nil?
new_key = chef_rest.put("#{api_base}/#{@actor}/keys/#{put_name}", to_hash)
# if the server returned a public_key, remove the create_key field, as we now have a key
if new_key["public_key"]
self.delete_create_key
end
Chef::Key.from_hash(self.to_hash.merge(new_key))
end
def save
create
rescue Net::HTTPServerException => e
if e.response.code == "409"
update
else
raise e
end
end
def destroy
if @name.nil?
raise Chef::Exceptions::MissingKeyAttribute, "the name field must be populated when delete is called"
end
chef_rest.delete("#{api_base}/#{@actor}/keys/#{@name}")
end
# Class methods
def self.from_hash(key_hash)
if key_hash.has_key?("user")
key = Chef::Key.new(key_hash["user"], "user")
elsif key_hash.has_key?("client")
key = Chef::Key.new(key_hash["client"], "client")
else
raise Chef::Exceptions::MissingKeyAttribute, "The hash passed to from_hash does not contain the key 'user' or 'client'. Please pass a hash that defines one of those keys."
end
key.name key_hash["name"] if key_hash.key?("name")
key.public_key key_hash["public_key"] if key_hash.key?("public_key")
key.private_key key_hash["private_key"] if key_hash.key?("private_key")
key.create_key key_hash["create_key"] if key_hash.key?("create_key")
key.expiration_date key_hash["expiration_date"] if key_hash.key?("expiration_date")
key
end
def self.from_json(json)
Chef::Key.from_hash(Chef::JSONCompat.from_json(json))
end
def self.json_create(json)
Chef.log_deprecation("Auto inflation of JSON data is deprecated. Please use Chef::Key#from_json or one of the load_by methods.")
Chef::Key.from_json(json)
end
def self.list_by_user(actor, inflate = false)
keys = Chef::ServerAPI.new(Chef::Config[:chef_server_root]).get("users/#{actor}/keys")
self.list(keys, actor, :load_by_user, inflate)
end
def self.list_by_client(actor, inflate = false)
keys = Chef::ServerAPI.new(Chef::Config[:chef_server_url]).get("clients/#{actor}/keys")
self.list(keys, actor, :load_by_client, inflate)
end
def self.load_by_user(actor, key_name)
response = Chef::ServerAPI.new(Chef::Config[:chef_server_root]).get("users/#{actor}/keys/#{key_name}")
Chef::Key.from_hash(response.merge({ "user" => actor }))
end
def self.load_by_client(actor, key_name)
response = Chef::ServerAPI.new(Chef::Config[:chef_server_url]).get("clients/#{actor}/keys/#{key_name}")
Chef::Key.from_hash(response.merge({ "client" => actor }))
end
def self.generate_fingerprint(public_key)
openssl_key_object = OpenSSL::PKey::RSA.new(public_key)
data_string = OpenSSL::ASN1::Sequence([
OpenSSL::ASN1::Integer.new(openssl_key_object.public_key.n),
OpenSSL::ASN1::Integer.new(openssl_key_object.public_key.e),
])
OpenSSL::Digest::SHA1.hexdigest(data_string.to_der).scan(/../).join(":")
end
private
def self.list(keys, actor, load_method_symbol, inflate)
if inflate
keys.inject({}) do |key_map, result|
name = result["name"]
key_map[name] = Chef::Key.send(load_method_symbol, actor, name)
key_map
end
else
keys
end
end
end
end
| 35.952555 | 179 | 0.639935 |
d54a6873f47a7c15bc58dcce5c1b23fdd9a2ad2e | 2,841 | ################################################################################
# Hashes and symbols: ##########################################################
################################################################################
#1. Define a hash with the keys ’one’, ’two’, and ’three’, and the values ’uno’,
# ’dos’, and ’tres’. Iterate over the hash, and for each key/value pair print
# out "’#{key}’ in Spanish is ’#{value}’".
eng_span = { 'one' => 'uno', 'two' => 'dos', 'three' => 'tres' }
eng_span.each do |k, v|
puts "#{k} in Spanish is #{v}."
end
################################################################################
#2. Create three hashes called person1, person2, and person3, with first and
# last names under the keys :first and :last. Then create a params hash so
# that params[:father] is person1, params[:mother] is person2, and
# params[:child] is person3. Verify that, for example, params[:father][:first]
# has the right value.
person1 = { first: 'Albert', last: 'Nordness' }
person2 = { first: 'Doris', Last: 'Nordness' }
person3 = { first: 'Annie', last: 'Hammond' }
params = { father: person1, mother: person2, child: person3 }
puts params[:father][:first]
################################################################################
#3. Define a hash with symbol keys corresponding to name, email, and
# a “password digest”, and values equal to your name, your email address, and
# a random string of 16 lower-case letters.
user_credentials = { name: 'Martin Fencl',
email: '[email protected]',
'password digest': ('a'..'z').to_a.shuffle[0..15].join }
puts user_credentials
puts user_credentials[:'password digest']
################################################################################
#4. Find an online version of the Ruby API and read about the Hash method merge.
# What is the value of the following expression?
#
# { "a" => 100, "b" => 200 }.merge({ "b" => 300 })
# > { "a" => 100, "b" => 200, "b" => 300 } #<= nope, ERROR; read specs!
merged_hash = { "a" => 100, "b" => 200 }.merge({ "b" => 300 })
puts merged_hash
merged_hash_2 = { "a" => 100, "b" => 200 }.merge({ "b" => 300, "c" => 400 })
puts merged_hash_2
################################################################################
################################################################################
puts "Extra notes: ############################################################"
# Speaking of Hashes,
# ... keep in mind the difference from Arrays when instantiating:
p 'Arrays: #######################'
a = Array.new
p a
p a[3]
a1 = Array.new( [0, 2, 1] )
p a1
p a1[3]
# ... but:
p 'Hashes: #######################'
h = Hash.new
p h
p h[:foo]
h1 = Hash.new( 0 ) #<= sets default value for any, even non-existant key
p h1
p h1[:foo]
| 37.381579 | 81 | 0.469201 |
e2a1ffdff6c2a14f175cca8cb29f615c2e84e2e0 | 2,104 | require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
# require "rails/test_unit/railtie"
Bundler.require
require "private_person"
require 'chalk_dust'
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
end
end
| 41.254902 | 99 | 0.73289 |
e83fde234915ef82df58edf0d20f741bb7ade5f0 | 27,758 | require 'abstract_unit'
# FIXME: crashes Ruby 1.9
class FilterTest < Test::Unit::TestCase
class TestController < ActionController::Base
before_filter :ensure_login
after_filter :clean_up
def show
render :inline => "ran action"
end
private
def ensure_login
@ran_filter ||= []
@ran_filter << "ensure_login"
end
def clean_up
@ran_after_filter ||= []
@ran_after_filter << "clean_up"
end
end
class ChangingTheRequirementsController < TestController
before_filter :ensure_login, :except => [:go_wild]
def go_wild
render :text => "gobble"
end
end
class TestMultipleFiltersController < ActionController::Base
before_filter :try_1
before_filter :try_2
before_filter :try_3
(1..3).each do |i|
define_method "fail_#{i}" do
render :text => i.to_s
end
end
protected
(1..3).each do |i|
define_method "try_#{i}" do
instance_variable_set :@try, i
if action_name == "fail_#{i}"
head(404)
end
end
end
end
class RenderingController < ActionController::Base
before_filter :render_something_else
def show
@ran_action = true
render :inline => "ran action"
end
private
def render_something_else
render :inline => "something else"
end
end
class ConditionalFilterController < ActionController::Base
def show
render :inline => "ran action"
end
def another_action
render :inline => "ran action"
end
def show_without_filter
render :inline => "ran action without filter"
end
private
def ensure_login
@ran_filter ||= []
@ran_filter << "ensure_login"
end
def clean_up_tmp
@ran_filter ||= []
@ran_filter << "clean_up_tmp"
end
def rescue_action(e) raise(e) end
end
class ConditionalCollectionFilterController < ConditionalFilterController
before_filter :ensure_login, :except => [ :show_without_filter, :another_action ]
end
class OnlyConditionSymController < ConditionalFilterController
before_filter :ensure_login, :only => :show
end
class ExceptConditionSymController < ConditionalFilterController
before_filter :ensure_login, :except => :show_without_filter
end
class BeforeAndAfterConditionController < ConditionalFilterController
before_filter :ensure_login, :only => :show
after_filter :clean_up_tmp, :only => :show
end
class OnlyConditionProcController < ConditionalFilterController
before_filter(:only => :show) {|c| c.instance_variable_set(:"@ran_proc_filter", true) }
end
class ExceptConditionProcController < ConditionalFilterController
before_filter(:except => :show_without_filter) {|c| c.instance_variable_set(:"@ran_proc_filter", true) }
end
class ConditionalClassFilter
def self.filter(controller) controller.instance_variable_set(:"@ran_class_filter", true) end
end
class OnlyConditionClassController < ConditionalFilterController
before_filter ConditionalClassFilter, :only => :show
end
class ExceptConditionClassController < ConditionalFilterController
before_filter ConditionalClassFilter, :except => :show_without_filter
end
class AnomolousYetValidConditionController < ConditionalFilterController
before_filter(ConditionalClassFilter, :ensure_login, Proc.new {|c| c.instance_variable_set(:"@ran_proc_filter1", true)}, :except => :show_without_filter) { |c| c.instance_variable_set(:"@ran_proc_filter2", true)}
end
class ConditionalOptionsFilter < ConditionalFilterController
before_filter :ensure_login, :if => Proc.new { |c| true }
before_filter :clean_up_tmp, :if => Proc.new { |c| false }
end
class EmptyFilterChainController < TestController
self.filter_chain.clear
def show
@action_executed = true
render :text => "yawp!"
end
end
class PrependingController < TestController
prepend_before_filter :wonderful_life
# skip_before_filter :fire_flash
private
def wonderful_life
@ran_filter ||= []
@ran_filter << "wonderful_life"
end
end
class SkippingAndLimitedController < TestController
skip_before_filter :ensure_login
before_filter :ensure_login, :only => :index
def index
render :text => 'ok'
end
def public
end
end
class SkippingAndReorderingController < TestController
skip_before_filter :ensure_login
before_filter :find_record
before_filter :ensure_login
private
def find_record
@ran_filter ||= []
@ran_filter << "find_record"
end
end
class ConditionalSkippingController < TestController
skip_before_filter :ensure_login, :only => [ :login ]
skip_after_filter :clean_up, :only => [ :login ]
before_filter :find_user, :only => [ :change_password ]
def login
render :inline => "ran action"
end
def change_password
render :inline => "ran action"
end
protected
def find_user
@ran_filter ||= []
@ran_filter << "find_user"
end
end
class ConditionalParentOfConditionalSkippingController < ConditionalFilterController
before_filter :conditional_in_parent, :only => [:show, :another_action]
after_filter :conditional_in_parent, :only => [:show, :another_action]
private
def conditional_in_parent
@ran_filter ||= []
@ran_filter << 'conditional_in_parent'
end
end
class ChildOfConditionalParentController < ConditionalParentOfConditionalSkippingController
skip_before_filter :conditional_in_parent, :only => :another_action
skip_after_filter :conditional_in_parent, :only => :another_action
end
class AnotherChildOfConditionalParentController < ConditionalParentOfConditionalSkippingController
skip_before_filter :conditional_in_parent, :only => :show
end
class ProcController < PrependingController
before_filter(proc { |c| c.instance_variable_set(:"@ran_proc_filter", true) })
end
class ImplicitProcController < PrependingController
before_filter { |c| c.instance_variable_set(:"@ran_proc_filter", true) }
end
class AuditFilter
def self.filter(controller)
controller.instance_variable_set(:"@was_audited", true)
end
end
class AroundFilter
def before(controller)
@execution_log = "before"
controller.class.execution_log << " before aroundfilter " if controller.respond_to? :execution_log
controller.instance_variable_set(:"@before_ran", true)
end
def after(controller)
controller.instance_variable_set(:"@execution_log", @execution_log + " and after")
controller.instance_variable_set(:"@after_ran", true)
controller.class.execution_log << " after aroundfilter " if controller.respond_to? :execution_log
end
end
class AppendedAroundFilter
def before(controller)
controller.class.execution_log << " before appended aroundfilter "
end
def after(controller)
controller.class.execution_log << " after appended aroundfilter "
end
end
class AuditController < ActionController::Base
before_filter(AuditFilter)
def show
render :text => "hello"
end
end
class AroundFilterController < PrependingController
around_filter AroundFilter.new
end
class BeforeAfterClassFilterController < PrependingController
begin
filter = AroundFilter.new
before_filter filter
after_filter filter
end
end
class MixedFilterController < PrependingController
cattr_accessor :execution_log
def initialize
@@execution_log = ""
end
before_filter { |c| c.class.execution_log << " before procfilter " }
prepend_around_filter AroundFilter.new
after_filter { |c| c.class.execution_log << " after procfilter " }
append_around_filter AppendedAroundFilter.new
end
class MixedSpecializationController < ActionController::Base
class OutOfOrder < StandardError; end
before_filter :first
before_filter :second, :only => :foo
def foo
render :text => 'foo'
end
def bar
render :text => 'bar'
end
protected
def first
@first = true
end
def second
raise OutOfOrder unless @first
end
end
class DynamicDispatchController < ActionController::Base
before_filter :choose
%w(foo bar baz).each do |action|
define_method(action) { render :text => action }
end
private
def choose
self.action_name = params[:choose]
end
end
class PrependingBeforeAndAfterController < ActionController::Base
prepend_before_filter :before_all
prepend_after_filter :after_all
before_filter :between_before_all_and_after_all
def before_all
@ran_filter ||= []
@ran_filter << 'before_all'
end
def after_all
@ran_filter ||= []
@ran_filter << 'after_all'
end
def between_before_all_and_after_all
@ran_filter ||= []
@ran_filter << 'between_before_all_and_after_all'
end
def show
render :text => 'hello'
end
end
class ErrorToRescue < Exception; end
class RescuingAroundFilterWithBlock
def filter(controller)
begin
yield
rescue ErrorToRescue => ex
controller.__send__ :render, :text => "I rescued this: #{ex.inspect}"
end
end
end
class RescuedController < ActionController::Base
around_filter RescuingAroundFilterWithBlock.new
def show
raise ErrorToRescue.new("Something made the bad noise.")
end
private
def rescue_action(exception)
raise exception
end
end
class NonYieldingAroundFilterController < ActionController::Base
before_filter :filter_one
around_filter :non_yielding_filter
before_filter :filter_two
after_filter :filter_three
def index
render :inline => "index"
end
#make sure the controller complains
def rescue_action(e); raise e; end
private
def filter_one
@filters ||= []
@filters << "filter_one"
end
def filter_two
@filters << "filter_two"
end
def non_yielding_filter
@filters << "zomg it didn't yield"
@filter_return_value
end
def filter_three
@filters << "filter_three"
end
end
def test_non_yielding_around_filters_not_returning_false_do_not_raise
controller = NonYieldingAroundFilterController.new
controller.instance_variable_set "@filter_return_value", true
assert_nothing_raised do
test_process(controller, "index")
end
end
def test_non_yielding_around_filters_returning_false_do_not_raise
controller = NonYieldingAroundFilterController.new
controller.instance_variable_set "@filter_return_value", false
assert_nothing_raised do
test_process(controller, "index")
end
end
def test_after_filters_are_not_run_if_around_filter_returns_false
controller = NonYieldingAroundFilterController.new
controller.instance_variable_set "@filter_return_value", false
test_process(controller, "index")
assert_equal ["filter_one", "zomg it didn't yield"], controller.assigns['filters']
end
def test_after_filters_are_not_run_if_around_filter_does_not_yield
controller = NonYieldingAroundFilterController.new
controller.instance_variable_set "@filter_return_value", true
test_process(controller, "index")
assert_equal ["filter_one", "zomg it didn't yield"], controller.assigns['filters']
end
def test_empty_filter_chain
assert_equal 0, EmptyFilterChainController.filter_chain.size
assert test_process(EmptyFilterChainController).template.assigns['action_executed']
end
def test_added_filter_to_inheritance_graph
assert_equal [ :ensure_login ], TestController.before_filters
end
def test_base_class_in_isolation
assert_equal [ ], ActionController::Base.before_filters
end
def test_prepending_filter
assert_equal [ :wonderful_life, :ensure_login ], PrependingController.before_filters
end
def test_running_filters
assert_equal %w( wonderful_life ensure_login ), test_process(PrependingController).template.assigns["ran_filter"]
end
def test_running_filters_with_proc
assert test_process(ProcController).template.assigns["ran_proc_filter"]
end
def test_running_filters_with_implicit_proc
assert test_process(ImplicitProcController).template.assigns["ran_proc_filter"]
end
def test_running_filters_with_class
assert test_process(AuditController).template.assigns["was_audited"]
end
def test_running_anomolous_yet_valid_condition_filters
response = test_process(AnomolousYetValidConditionController)
assert_equal %w( ensure_login ), response.template.assigns["ran_filter"]
assert response.template.assigns["ran_class_filter"]
assert response.template.assigns["ran_proc_filter1"]
assert response.template.assigns["ran_proc_filter2"]
response = test_process(AnomolousYetValidConditionController, "show_without_filter")
assert_equal nil, response.template.assigns["ran_filter"]
assert !response.template.assigns["ran_class_filter"]
assert !response.template.assigns["ran_proc_filter1"]
assert !response.template.assigns["ran_proc_filter2"]
end
def test_running_conditional_options
response = test_process(ConditionalOptionsFilter)
assert_equal %w( ensure_login ), response.template.assigns["ran_filter"]
end
def test_running_collection_condition_filters
assert_equal %w( ensure_login ), test_process(ConditionalCollectionFilterController).template.assigns["ran_filter"]
assert_equal nil, test_process(ConditionalCollectionFilterController, "show_without_filter").template.assigns["ran_filter"]
assert_equal nil, test_process(ConditionalCollectionFilterController, "another_action").template.assigns["ran_filter"]
end
def test_running_only_condition_filters
assert_equal %w( ensure_login ), test_process(OnlyConditionSymController).template.assigns["ran_filter"]
assert_equal nil, test_process(OnlyConditionSymController, "show_without_filter").template.assigns["ran_filter"]
assert test_process(OnlyConditionProcController).template.assigns["ran_proc_filter"]
assert !test_process(OnlyConditionProcController, "show_without_filter").template.assigns["ran_proc_filter"]
assert test_process(OnlyConditionClassController).template.assigns["ran_class_filter"]
assert !test_process(OnlyConditionClassController, "show_without_filter").template.assigns["ran_class_filter"]
end
def test_running_except_condition_filters
assert_equal %w( ensure_login ), test_process(ExceptConditionSymController).template.assigns["ran_filter"]
assert_equal nil, test_process(ExceptConditionSymController, "show_without_filter").template.assigns["ran_filter"]
assert test_process(ExceptConditionProcController).template.assigns["ran_proc_filter"]
assert !test_process(ExceptConditionProcController, "show_without_filter").template.assigns["ran_proc_filter"]
assert test_process(ExceptConditionClassController).template.assigns["ran_class_filter"]
assert !test_process(ExceptConditionClassController, "show_without_filter").template.assigns["ran_class_filter"]
end
def test_running_before_and_after_condition_filters
assert_equal %w( ensure_login clean_up_tmp), test_process(BeforeAndAfterConditionController).template.assigns["ran_filter"]
assert_equal nil, test_process(BeforeAndAfterConditionController, "show_without_filter").template.assigns["ran_filter"]
end
def test_around_filter
controller = test_process(AroundFilterController)
assert controller.template.assigns["before_ran"]
assert controller.template.assigns["after_ran"]
end
def test_before_after_class_filter
controller = test_process(BeforeAfterClassFilterController)
assert controller.template.assigns["before_ran"]
assert controller.template.assigns["after_ran"]
end
def test_having_properties_in_around_filter
controller = test_process(AroundFilterController)
assert_equal "before and after", controller.template.assigns["execution_log"]
end
def test_prepending_and_appending_around_filter
controller = test_process(MixedFilterController)
assert_equal " before aroundfilter before procfilter before appended aroundfilter " +
" after appended aroundfilter after aroundfilter after procfilter ",
MixedFilterController.execution_log
end
def test_rendering_breaks_filtering_chain
response = test_process(RenderingController)
assert_equal "something else", response.body
assert !response.template.assigns["ran_action"]
end
def test_filters_with_mixed_specialization_run_in_order
assert_nothing_raised do
response = test_process(MixedSpecializationController, 'bar')
assert_equal 'bar', response.body
end
assert_nothing_raised do
response = test_process(MixedSpecializationController, 'foo')
assert_equal 'foo', response.body
end
end
def test_dynamic_dispatch
%w(foo bar baz).each do |action|
request = ActionController::TestRequest.new
request.query_parameters[:choose] = action
response = DynamicDispatchController.process(request, ActionController::TestResponse.new)
assert_equal action, response.body
end
end
def test_running_prepended_before_and_after_filter
assert_equal 3, PrependingBeforeAndAfterController.filter_chain.length
response = test_process(PrependingBeforeAndAfterController)
assert_equal %w( before_all between_before_all_and_after_all after_all ), response.template.assigns["ran_filter"]
end
def test_skipping_and_limiting_controller
assert_equal %w( ensure_login ), test_process(SkippingAndLimitedController, "index").template.assigns["ran_filter"]
assert_nil test_process(SkippingAndLimitedController, "public").template.assigns["ran_filter"]
end
def test_skipping_and_reordering_controller
assert_equal %w( find_record ensure_login ), test_process(SkippingAndReorderingController, "index").template.assigns["ran_filter"]
end
def test_conditional_skipping_of_filters
assert_nil test_process(ConditionalSkippingController, "login").template.assigns["ran_filter"]
assert_equal %w( ensure_login find_user ), test_process(ConditionalSkippingController, "change_password").template.assigns["ran_filter"]
assert_nil test_process(ConditionalSkippingController, "login").template.controller.instance_variable_get("@ran_after_filter")
assert_equal %w( clean_up ), test_process(ConditionalSkippingController, "change_password").template.controller.instance_variable_get("@ran_after_filter")
end
def test_conditional_skipping_of_filters_when_parent_filter_is_also_conditional
assert_equal %w( conditional_in_parent conditional_in_parent ), test_process(ChildOfConditionalParentController).template.assigns['ran_filter']
assert_nil test_process(ChildOfConditionalParentController, 'another_action').template.assigns['ran_filter']
end
def test_condition_skipping_of_filters_when_siblings_also_have_conditions
assert_equal %w( conditional_in_parent conditional_in_parent ), test_process(ChildOfConditionalParentController).template.assigns['ran_filter'], "1"
assert_equal nil, test_process(AnotherChildOfConditionalParentController).template.assigns['ran_filter']
assert_equal %w( conditional_in_parent conditional_in_parent ), test_process(ChildOfConditionalParentController).template.assigns['ran_filter']
end
def test_changing_the_requirements
assert_equal nil, test_process(ChangingTheRequirementsController, "go_wild").template.assigns['ran_filter']
end
def test_a_rescuing_around_filter
response = nil
assert_nothing_raised do
response = test_process(RescuedController)
end
assert response.success?
assert_equal("I rescued this: #<FilterTest::ErrorToRescue: Something made the bad noise.>", response.body)
end
private
def test_process(controller, action = "show")
ActionController::Base.class_eval { include ActionController::ProcessWithTest } unless ActionController::Base < ActionController::ProcessWithTest
request = ActionController::TestRequest.new
request.action = action
controller = controller.new if controller.is_a?(Class)
controller.process_with_test(request, ActionController::TestResponse.new)
end
end
class PostsController < ActionController::Base
def rescue_action(e); raise e; end
module AroundExceptions
class Error < StandardError ; end
class Before < Error ; end
class After < Error ; end
end
include AroundExceptions
class DefaultFilter
include AroundExceptions
end
module_eval %w(raises_before raises_after raises_both no_raise no_filter).map { |action| "def #{action}; default_action end" }.join("\n")
private
def default_action
render :inline => "#{action_name} called"
end
end
class ControllerWithSymbolAsFilter < PostsController
around_filter :raise_before, :only => :raises_before
around_filter :raise_after, :only => :raises_after
around_filter :without_exception, :only => :no_raise
private
def raise_before
raise Before
yield
end
def raise_after
yield
raise After
end
def without_exception
# Do stuff...
1 + 1
yield
# Do stuff...
1 + 1
end
end
class ControllerWithFilterClass < PostsController
class YieldingFilter < DefaultFilter
def self.filter(controller)
yield
raise After
end
end
around_filter YieldingFilter, :only => :raises_after
end
class ControllerWithFilterInstance < PostsController
class YieldingFilter < DefaultFilter
def filter(controller)
yield
raise After
end
end
around_filter YieldingFilter.new, :only => :raises_after
end
class ControllerWithFilterMethod < PostsController
class YieldingFilter < DefaultFilter
def filter(controller)
yield
raise After
end
end
around_filter YieldingFilter.new.method(:filter), :only => :raises_after
end
class ControllerWithProcFilter < PostsController
around_filter(:only => :no_raise) do |c,b|
c.instance_variable_set(:"@before", true)
b.call
c.instance_variable_set(:"@after", true)
end
end
class ControllerWithNestedFilters < ControllerWithSymbolAsFilter
around_filter :raise_before, :raise_after, :without_exception, :only => :raises_both
end
class ControllerWithAllTypesOfFilters < PostsController
before_filter :before
around_filter :around
after_filter :after
around_filter :around_again
private
def before
@ran_filter ||= []
@ran_filter << 'before'
end
def around
@ran_filter << 'around (before yield)'
yield
@ran_filter << 'around (after yield)'
end
def after
@ran_filter << 'after'
end
def around_again
@ran_filter << 'around_again (before yield)'
yield
@ran_filter << 'around_again (after yield)'
end
end
class ControllerWithTwoLessFilters < ControllerWithAllTypesOfFilters
skip_filter :around_again
skip_filter :after
end
class YieldingAroundFiltersTest < Test::Unit::TestCase
include PostsController::AroundExceptions
def test_filters_registering
assert_equal 1, ControllerWithFilterMethod.filter_chain.size
assert_equal 1, ControllerWithFilterClass.filter_chain.size
assert_equal 1, ControllerWithFilterInstance.filter_chain.size
assert_equal 3, ControllerWithSymbolAsFilter.filter_chain.size
assert_equal 6, ControllerWithNestedFilters.filter_chain.size
assert_equal 4, ControllerWithAllTypesOfFilters.filter_chain.size
end
def test_base
controller = PostsController
assert_nothing_raised { test_process(controller,'no_raise') }
assert_nothing_raised { test_process(controller,'raises_before') }
assert_nothing_raised { test_process(controller,'raises_after') }
assert_nothing_raised { test_process(controller,'no_filter') }
end
def test_with_symbol
controller = ControllerWithSymbolAsFilter
assert_nothing_raised { test_process(controller,'no_raise') }
assert_raise(Before) { test_process(controller,'raises_before') }
assert_raise(After) { test_process(controller,'raises_after') }
assert_nothing_raised { test_process(controller,'no_raise') }
end
def test_with_class
controller = ControllerWithFilterClass
assert_nothing_raised { test_process(controller,'no_raise') }
assert_raise(After) { test_process(controller,'raises_after') }
end
def test_with_instance
controller = ControllerWithFilterInstance
assert_nothing_raised { test_process(controller,'no_raise') }
assert_raise(After) { test_process(controller,'raises_after') }
end
def test_with_method
controller = ControllerWithFilterMethod
assert_nothing_raised { test_process(controller,'no_raise') }
assert_raise(After) { test_process(controller,'raises_after') }
end
def test_with_proc
controller = test_process(ControllerWithProcFilter,'no_raise')
assert controller.template.assigns['before']
assert controller.template.assigns['after']
end
def test_nested_filters
controller = ControllerWithNestedFilters
assert_nothing_raised do
begin
test_process(controller,'raises_both')
rescue Before, After
end
end
assert_raise Before do
begin
test_process(controller,'raises_both')
rescue After
end
end
end
def test_filter_order_with_all_filter_types
controller = test_process(ControllerWithAllTypesOfFilters,'no_raise')
assert_equal 'before around (before yield) around_again (before yield) around_again (after yield) around (after yield) after',controller.template.assigns['ran_filter'].join(' ')
end
def test_filter_order_with_skip_filter_method
controller = test_process(ControllerWithTwoLessFilters,'no_raise')
assert_equal 'before around (before yield) around (after yield)',controller.template.assigns['ran_filter'].join(' ')
end
def test_first_filter_in_multiple_before_filter_chain_halts
controller = ::FilterTest::TestMultipleFiltersController.new
response = test_process(controller, 'fail_1')
assert_equal ' ', response.body
assert_equal 1, controller.instance_variable_get(:@try)
assert controller.instance_variable_get(:@before_filter_chain_aborted)
end
def test_second_filter_in_multiple_before_filter_chain_halts
controller = ::FilterTest::TestMultipleFiltersController.new
response = test_process(controller, 'fail_2')
assert_equal ' ', response.body
assert_equal 2, controller.instance_variable_get(:@try)
assert controller.instance_variable_get(:@before_filter_chain_aborted)
end
def test_last_filter_in_multiple_before_filter_chain_halts
controller = ::FilterTest::TestMultipleFiltersController.new
response = test_process(controller, 'fail_3')
assert_equal ' ', response.body
assert_equal 3, controller.instance_variable_get(:@try)
assert controller.instance_variable_get(:@before_filter_chain_aborted)
end
protected
def test_process(controller, action = "show")
ActionController::Base.class_eval { include ActionController::ProcessWithTest } unless ActionController::Base < ActionController::ProcessWithTest
request = ActionController::TestRequest.new
request.action = action
controller = controller.new if controller.is_a?(Class)
controller.process_with_test(request, ActionController::TestResponse.new)
end
end
| 31.329571 | 216 | 0.749514 |
390ba692c07e796e78188599afedf16710baaf8a | 662 | # frozen_string_literal: true
RSpec.describe Lambda::AnswerCallbackQuery, :with_lambda do
let(:event) { { 'Records' => [record] } }
let(:callback_query) { json_fixture('telegram/callback_query.json') }
let(:record) { { 'Sns' => { 'Message' => body } } }
let(:body) { callback_query.to_json }
let(:stub_url) { "https://api.telegram.org/bot#{ENV['TELEGRAM_BOT_API_TOKEN']}/answerCallbackQuery" }
before do
success = file_fixture('telegram/successful_response.json')
stub_request(:post, stub_url).to_return(status: 200, body: success)
end
it 'works' do
result
expect(a_request(:post, stub_url)).to have_been_made.once
end
end
| 30.090909 | 103 | 0.697885 |
ff42f051a2292e2515b3bc69d7e88e8cdb878b8a | 767 | cask 'riot' do
version '1.6.7'
sha256 '97a2413c050df71f293de0ce392aec567de847c18bb3e7f1c11112e1a5504948'
url "https://packages.riot.im/desktop/install/macos/Riot-#{version}.dmg"
appcast 'https://github.com/vector-im/riot-desktop/releases.atom'
name 'Riot'
homepage 'https://about.riot.im/'
auto_updates true
app 'Riot.app'
zap trash: [
'~/Library/Application Support/Riot',
'~/Library/Caches/im.riot.app',
'~/Library/Caches/im.riot.app.ShipIt',
'~/Library/Logs/Riot',
'~/Library/Preferences/im.riot.app.helper.plist',
'~/Library/Preferences/im.riot.app.plist',
'~/Library/Saved Application State/im.riot.app.savedState',
]
end
| 31.958333 | 75 | 0.621904 |
bbb3eab773e9de375459e06b750d304ca12e1ba9 | 105 | class PlayedCard < ApplicationRecord
belongs_to :user
belongs_to :white_card
belongs_to :round
end
| 17.5 | 36 | 0.8 |
39ecadb4270dc4aebc385a56c4a2d0cffc9820fe | 215 | MRuby::Gem::Specification.new('orgf-filesystem') do |spec|
spec.license = 'Apache-2.0'
spec.author = 'Ramiro Rojo'
spec.add_dependency 'orgf-dependencies'
spec.add_dependency 'mruby-compiler'
end
| 23.888889 | 59 | 0.702326 |
62c89d644c223c31262ac827bf7d3929df69e91b | 2,373 | ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'
class ActiveSupport::TestCase
include Authorization::TestHelper
# Transactional fixtures accelerate your tests by wrapping each test method
# in a transaction that's rolled back on completion. This ensures that the
# test database remains unchanged so your fixtures don't have to be reloaded
# between every test method. Fewer database queries means faster tests.
#
# Read Mike Clark's excellent walkthrough at
# http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting
#
# Every Active Record database supports transactions except MyISAM tables
# in MySQL. Turn off transactional fixtures in this case; however, if you
# don't care one way or the other, switching from MyISAM to InnoDB tables
# is recommended.
#
# The only drawback to using transactional fixtures is when you actually
# need to test transactions. Since your test is bracketed by a transaction,
# any transactions started in your code will be automatically rolled back.
self.use_transactional_fixtures = true
# Instantiated fixtures are slow, but give you @david where otherwise you
# would need people(:david). If you don't want to migrate your existing
# test cases which use the @david style and don't mind the speed hit (each
# instantiated fixtures translates to a database query per test method),
# then set this back to true.
self.use_instantiated_fixtures = false
# Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
#
# Note: You'll currently still have to declare fixtures explicitly in integration tests
# -- they do not yet inherit this setting
fixtures :all
protected
def create_guild(user)
return user.guilds.create(
:name => "The Epic Guild"+(rand+999).to_s,
:game => "World Domination",
:server => "http://google.com",
:about => "We will controll all shit on this planet!",
:typ => GT_GUILD
)
end
def create_user(options = {})
record = User.create({ :login => 'dude'+(rand+999).to_s, :email => '[email protected]', :password => 'this_is_booring_password', :password_confirmation => 'this_is_booring_password', "terms_of_service"=>"1" }.merge(options))
end
# Add more helper methods to be used by all tests here...
end
| 43.145455 | 227 | 0.73367 |
ff50386b0e8121324085631197acf4b79f5aae55 | 688 | =begin
#Datadog API V1 Collection
#Collection of all Datadog Public endpoints.
The version of the OpenAPI document: 1.0
Contact: [email protected]
Generated by: https://github.com/DataDog/datadog-api-client-ruby/tree/master/.generator
Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
This product includes software developed at Datadog (https://www.datadoghq.com/).
Copyright 2020-Present Datadog, Inc.
=end
require 'date'
require 'time'
module DatadogAPIClient::V1
# Type of the alert value widget.
class AlertValueWidgetDefinitionType
include BaseEnumModel
ALERT_VALUE = "alert_value".freeze
end
end
| 25.481481 | 107 | 0.784884 |
4abeb6c46dc790d5175773ee1291b921b0321601 | 195 | class AddMarketGroupRefToEveItem < ActiveRecord::Migration[4.2]
def change
add_reference :eve_items, :market_group, index: true
remove_column :eve_items, :cpp_market_group_id
end
end
| 27.857143 | 63 | 0.784615 |
38cbe536e88af940cdad69c1a808333fd0ea647e | 404 | # frozen_string_literal: true
$stdout.sync = true
require 'listen'
namespace :rails_hotreload do
desc 'Start watching file changes. Sample: bin/rails rails_hotreload:start app/assets/builds'
task start: :environment do
paths = (ARGV[0] || 'app/assets/builds,app/views/').to_s.split(',')
paths = paths.map { |p| Rails.root.join(p).to_s }
RailsHotreload::Checker.new(paths).call
end
end
| 31.076923 | 95 | 0.717822 |
037fa5fbc30bceafd95e6d35deaa3b0193847bf3 | 179 | # myapp.rb
require 'sinatra'
require 'rest-client'
require 'json'
get '/' do
url = 'http://jsonplaceholder.typicode.com/users'
JSON.parse(RestClient.get(url))[0]['name']
end
| 17.9 | 51 | 0.698324 |
1d3f2bb4b295bcc30aa3d420f6f917ee2dbfc9f5 | 743 | class User < ApplicationRecord
has_one :cart
has_many :user_outfits
has_many :outfits, through: :user_outfits
validates_uniqueness_of :email
validates_presence_of :first_name, :last_name, :email, :birth_date
has_secure_password
def full_name
self.first_name + " " + self.last_name
end
def birthday
self.birth_date.to_formatted_s(:long_ordinal)[0..-13]
end
def height_to_ft
divmod_output = self.height.divmod(12)
"#{divmod_output[0]} ft, #{divmod_output[1]} in"
end
def self.create_guest
email_prefix = (1..20000000).to_a.sample.to_s
self.create(first_name: "GUEST #{Time.now}", last_name: 'USER', email: "#{email_prefix}" + "@gmail.com", birth_date: DateTime.new(1988, 9, 27))
end
end
| 25.62069 | 147 | 0.71467 |
b91555a7d691ab598557ab2ae59f24450872fc39 | 52 | module AuthForum
module LineItemsHelper
end
end
| 10.4 | 24 | 0.807692 |
01e05e4623e69a678e6f514fd03a6a5a13559f7c | 7,804 | #/usr/bin/env ruby
require 'fox16'
require 'Clipboard'
require 'logger'
require_relative "ProcessadorDePendencias"
include Fox
class ProcessadorDePendenciasGUI < FXMainWindow
include ProcessadorDePendencias
def initialize(app)
Thread.abort_on_exception=true
# Invoke base class initialize first
super(app, "Processador de pendencias", opts: DECOR_ALL)
@errorLog = Logger.new 'erros.log', 10
@missingProposalsLog = Logger.new 'Propostas não encontradas.log', "daily"
@missingProposalsLog.formatter = proc do |severity, datetime, progname, msg|
" #{datetime.strftime("%d/%m/%Y %H:%M:%S")} | #{msg}\n"
end
@elements = Array.new
#Create a tooltip
FXToolTip.new(self.getApp())
### Controls on top
controls = FXVerticalFrame.new(self, LAYOUT_SIDE_TOP|LAYOUT_FILL_X,
padLeft: 30, padRight: 30, padTop: 10, padBottom: 10)
@elements << controlGroup = FXGroupBox.new(controls, "Selecione o banco sendo processado", GROUPBOX_TITLE_CENTER|FRAME_RIDGE|LAYOUT_SIDE_TOP|LAYOUT_FILL_X)
@elements << optionsPopup = FXPopup.new(controlGroup)
["Detecção automática", "Propostas na primeira coluna", "Itaú", "OLÉ", "HELP", "INTERMED EMPREST", "INTERMED CART", "Daycoval", "Centelem", "Bradesco", "CCB", "Bons", "Safra", "Sabemi", "PAN Consignado", "PAN Cartão", "Banrisul"].each { |opt| FXOption.new(optionsPopup, opt) }
@bank_select = FXOptionMenu.new controlGroup, optionsPopup, opts: FRAME_THICK|FRAME_RAISED|ICON_BEFORE_TEXT|LAYOUT_FILL_X
@elements << controlGroup = FXGroupBox.new(controls, "Selecione a planilha a ser processada", GROUPBOX_TITLE_CENTER|FRAME_RIDGE|LAYOUT_SIDE_TOP|LAYOUT_FILL_X)
@progress_keeper = FXProgressBar.new(controlGroup, opts: PROGRESSBAR_NORMAL|PROGRESSBAR_HORIZONTAL|LAYOUT_FILL_X|LAYOUT_SIDE_BOTTOM|PROGRESSBAR_PERCENTAGE)
@progress_keeper.barColor = FXRGB(0, 150, 0)
@progress_keeper.textColor = FXRGB(0, 0, 0)
@selectSpreadsheetBttn = FXButton.new(controlGroup, "Selecionar planilha", opts: LAYOUT_FILL_X|FRAME_THICK|FRAME_RIDGE|BUTTON_DEFAULT)
setupSelectSpreadsheetBttn
@elements << FXLabel.new(self, "contato: [email protected]", opts: JUSTIFY_CENTER_X|LAYOUT_SIDE_BOTTOM)
@elements << FXHorizontalSeparator.new(self, LAYOUT_SIDE_BOTTOM|LAYOUT_FILL_X|SEPARATOR_GROOVE)
### Tables
@elements << failedProposalsFrame = FXVerticalFrame.new(self, LAYOUT_SIDE_RIGHT|FRAME_NONE|LAYOUT_FILL_Y, padRight: 30, padLeft: 10)
@elements << box = FXGroupBox.new(failedProposalsFrame, "Propostas não encontradas", GROUPBOX_TITLE_CENTER|FRAME_RIDGE|LAYOUT_FILL_Y|LAYOUT_FILL_X, padding: 10)
@failedProposalsTable = nil
@elements << FXButton.new(box, "Copiar para área de transferência", opts: LAYOUT_SIDE_BOTTOM|FRAME_THICK|FRAME_RIDGE|LAYOUT_FILL_X).connect(SEL_COMMAND) do
copyContentsOfTable @failedProposalsTable
end
@failedProposalsTable = FXTable.new(box, opts: LAYOUT_CENTER_X|LAYOUT_CENTER_Y|LAYOUT_FILL_X|LAYOUT_FILL_Y|TABLE_COL_SIZABLE)
@failedProposalsTable.rowHeaderWidth = 30
@failedProposalsTable.visibleRows = 10
@failedProposalsTable.visibleColumns = 1
@failedProposalsTable.setTableSize 100, 1
@failedProposalsTable.editable = false
@elements << processedProposalsFrame = FXVerticalFrame.new(self, LAYOUT_SIDE_LEFT|FRAME_NONE|LAYOUT_FILL_Y|LAYOUT_FILL_X, padLeft: 30, padRight: 10)
@elements << box = FXGroupBox.new(processedProposalsFrame, "Propostas encontradas", GROUPBOX_TITLE_CENTER|FRAME_RIDGE|LAYOUT_FILL_Y|LAYOUT_FILL_X, padding: 10)
@processedProposalsTable = nil
@elements << FXButton.new(box, "Copiar para área de transferência", opts: LAYOUT_SIDE_BOTTOM|FRAME_THICK|FRAME_RIDGE|LAYOUT_FILL_X).connect(SEL_COMMAND) do
copyContentsOfTable @processedProposalsTable
end
@processedProposalsTable = FXTable.new(box, opts: LAYOUT_CENTER_X|LAYOUT_CENTER_Y|LAYOUT_FILL_X|LAYOUT_FILL_Y|TABLE_COL_SIZABLE)
@processedProposalsTable.rowHeaderWidth = 30
@processedProposalsTable.visibleRows = 10
@processedProposalsTable.visibleColumns = 3
@processedProposalsTable.setTableSize 20, 3
@processedProposalsTable.editable = false
end
def create
super
show(PLACEMENT_SCREEN)
end
def insertProcessedProposalsToTable (processedProposals, failedProposals)
if processedProposals.empty?
@processedProposalsTable.setTableSize 1,3
else
@processedProposalsTable.setTableSize(processedProposals.length, processedProposals.collect(&:length).max)
end
processedProposals.each_with_index do |values, i|
values.each_with_index do |v, j|
@processedProposalsTable.setItemText(i,j, v.to_s.strip)
end
end
rowNumber = if failedProposals.empty? then 1 else failedProposals.length end
@failedProposalsTable.setTableSize rowNumber, 1
failedProposals.each_with_index {|p, i| @failedProposalsTable.setItemText(i,0, p.to_s.strip)}
end
def processSpreadsheet filename
@selectSpreadsheetBttn.connect(SEL_COMMAND) do
FXMessageBox::information self, MBOX_OK, " Aguarde...", "Aguarde o processamento da planilha!"
end
@selectSpreadsheetBttn.text = "Aguarde..."
@processThread = Thread.new(self) do |window|
Thread::abort_on_exception = true
begin
puts "Starting main process thread"
processedProposals, failedProposals = recoverProposalNumbersAndStateOfProposals(filename, @bank_select.current.to_s, @progress_keeper)
puts "Done processing proposals, proposals found: #{processedProposals.length - 1}, failed proposals: #{failedProposals.length}"
unless failedProposals.empty?
failedProposalsMessage = "As seguintes propostas não puderam ser localizadas: " + failedProposals.join(", ")
@missingProposalsLog.info failedProposalsMessage
end
insertProcessedProposalsToTable processedProposals, failedProposals
doneMessage = "#{processedProposals.length - 1} propostas encontradas"
doneMessage += " e #{failedProposals.length} propostas não puderam ser localizadas" unless failedProposals.empty?
getApp.addChore {FXMessageBox::warning self, MBOX_OK, " Algo deu errado...", doneMessage}
rescue RuntimeError => err
@errorLog.error err
getApp.addChore {FXMessageBox::error self, MBOX_OK, " Algo deu errado...", err.message}
rescue Exception => exception
@errorLog.error exception
getApp.addChore {FXMessageBox::warning self, MBOX_OK, " Algo deu errado...", "Algo muito errado aconteceu, favor entre em contato com a equipe de suporte!"}
ensure
setupSelectSpreadsheetBttn
@progress_keeper.progress = @progress_keeper.total = 0
puts "Main thread finished"
end
end
end
def setupSelectSpreadsheetBttn
@selectSpreadsheetBttn.text = "Selecionar planilha"
@selectSpreadsheetBttn.connect(SEL_COMMAND) do
dialog = FXFileDialog.new(self, "Selecione a planilha de pendencias")
dialog.selectMode = SELECTFILE_EXISTING
dialog.patternList = ["Excel Files (*.xls,*.xlsx)"]
if dialog.execute != 0
processSpreadsheet dialog.filename
end
end
end
def copyContentsOfTable table
excelFriendlyContent = String.new
table.getNumRows.times do |r|
arr = Array.new
table.getNumColumns.times do |c|
arr << table.getItemText(r,c)
end
excelFriendlyContent += arr.collect{|s| "\"" + s.strip + "\""}.join("\t") + "\n"
end
Clipboard.copy excelFriendlyContent.strip
end
end
app = FXApp.new "ProcessadorDePendencias", "Processamento de planilhas de pendencias"
ProcessadorDePendenciasGUI.new app
app.create
app.run | 46.730539 | 280 | 0.736545 |
f7596dba29bff3a4f8018abbc7af35ea649f8a98 | 10,895 | # Copyright 2010-2012 Wincent Colaiuta. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
require 'command-t/finder/buffer_finder'
require 'command-t/finder/jump_finder'
require 'command-t/finder/file_finder'
require 'command-t/finder/tag_finder'
require 'command-t/match_window'
require 'command-t/prompt'
require 'command-t/vim/path_utilities'
module CommandT
class Controller
include VIM::PathUtilities
def initialize
@prompt = Prompt.new
end
def show_buffer_finder
@path = VIM::pwd
@active_finder = buffer_finder
show
end
def show_jump_finder
@path = VIM::pwd
@active_finder = jump_finder
show
end
def show_tag_finder
@path = VIM::pwd
@active_finder = tag_finder
show
end
def show_file_finder
# optional parameter will be desired starting directory, or ""
@path = File.expand_path(::VIM::evaluate('a:arg'), VIM::pwd)
@active_finder = file_finder
file_finder.path = @path
show
rescue Errno::ENOENT
# probably a problem with the optional parameter
@match_window.print_no_such_file_or_directory
end
def hide
@match_window.close
if VIM::Window.select @initial_window
if @initial_buffer.number == 0
# upstream bug: buffer number misreported as 0
# see: https://wincent.com/issues/1617
::VIM::command "silent b #{@initial_buffer.name}"
else
::VIM::command "silent b #{@initial_buffer.number}"
end
end
end
def refresh
return unless @active_finder && @active_finder.respond_to?(:flush)
@active_finder.flush
list_matches
end
def flush
@max_height = nil
@min_height = nil
@file_finder = nil
@tag_finder = nil
end
def handle_key
key = ::VIM::evaluate('a:arg').to_i.chr
if @focus == @prompt
@prompt.add! key
list_matches
else
@match_window.find key
end
end
def backspace
if @focus == @prompt
@prompt.backspace!
list_matches
end
end
def delete
if @focus == @prompt
@prompt.delete!
list_matches
end
end
def accept_selection options = {}
selection = @match_window.selection
hide
open_selection(selection, options) unless selection.nil?
end
def toggle_focus
@focus.unfocus # old focus
@focus = @focus == @prompt ? @match_window : @prompt
@focus.focus # new focus
end
def cancel
hide
end
def select_next
@match_window.select_next
end
def select_prev
@match_window.select_prev
end
def clear
@prompt.clear!
list_matches
end
def cursor_left
@prompt.cursor_left if @focus == @prompt
end
def cursor_right
@prompt.cursor_right if @focus == @prompt
end
def cursor_end
@prompt.cursor_end if @focus == @prompt
end
def cursor_start
@prompt.cursor_start if @focus == @prompt
end
def leave
@match_window.leave
end
def unload
@match_window.unload
end
private
def show
@initial_window = $curwin
@initial_buffer = $curbuf
@match_window = MatchWindow.new \
:highlight_color => get_string('g:CommandTHighlightColor'),
:match_window_at_top => get_bool('g:CommandTMatchWindowAtTop'),
:match_window_reverse => get_bool('g:CommandTMatchWindowReverse'),
:min_height => min_height,
:prompt => @prompt
@focus = @prompt
@prompt.focus
register_for_key_presses
clear # clears prompt and lists matches
end
def max_height
@max_height ||= get_number('g:CommandTMaxHeight') || 0
end
def min_height
@min_height ||= begin
min_height = get_number('g:CommandTMinHeight') || 0
min_height = max_height if max_height != 0 && min_height > max_height
min_height
end
end
def get_number name
VIM::exists?(name) ? ::VIM::evaluate("#{name}").to_i : nil
end
def get_bool name
VIM::exists?(name) ? ::VIM::evaluate("#{name}").to_i != 0 : nil
end
def get_string name
VIM::exists?(name) ? ::VIM::evaluate("#{name}").to_s : nil
end
# expect a string or a list of strings
def get_list_or_string name
return nil unless VIM::exists?(name)
list_or_string = ::VIM::evaluate("#{name}")
if list_or_string.kind_of?(Array)
list_or_string.map { |item| item.to_s }
else
list_or_string.to_s
end
end
# Backslash-escape space, \, |, %, #, "
def sanitize_path_string str
# for details on escaping command-line mode arguments see: :h :
# (that is, help on ":") in the Vim documentation.
str.gsub(/[ \\|%#"]/, '\\\\\0')
end
def default_open_command
if !get_bool('&hidden') && get_bool('&modified')
'sp'
else
'e'
end
end
def ensure_appropriate_window_selection
# normally we try to open the selection in the current window, but there
# is one exception:
#
# - we don't touch any "unlisted" buffer with buftype "nofile" (such as
# NERDTree or MiniBufExplorer); this is to avoid things like the "Not
# enough room" error which occurs when trying to open in a split in a
# shallow (potentially 1-line) buffer like MiniBufExplorer is current
#
# Other "unlisted" buffers, such as those with buftype "help" are treated
# normally.
initial = $curwin
while true do
break unless ::VIM::evaluate('&buflisted').to_i == 0 &&
::VIM::evaluate('&buftype').to_s == 'nofile'
::VIM::command 'wincmd w' # try next window
break if $curwin == initial # have already tried all
end
end
def open_selection selection, options = {}
command = options[:command] || default_open_command
selection = File.expand_path selection, @path
selection = relative_path_under_working_directory selection
selection = sanitize_path_string selection
selection = File.join('.', selection) if selection =~ /^\+/
ensure_appropriate_window_selection
@active_finder.open_selection command, selection, options
end
def map key, function, param = nil
::VIM::command "noremap <silent> <buffer> #{key} " \
":call CommandT#{function}(#{param})<CR>"
end
def term
@term ||= ::VIM::evaluate('&term')
end
def register_for_key_presses
# "normal" keys (interpreted literally)
numbers = ('0'..'9').to_a.join
lowercase = ('a'..'z').to_a.join
uppercase = lowercase.upcase
punctuation = '<>`@#~!"$%&/()=+*-_.,;:?\\\'{}[] ' # and space
(numbers + lowercase + uppercase + punctuation).each_byte do |b|
map "<Char-#{b}>", 'HandleKey', b
end
# "special" keys (overridable by settings)
{
'AcceptSelection' => '<CR>',
'AcceptSelectionSplit' => ['<C-CR>', '<C-s>'],
'AcceptSelectionTab' => '<C-t>',
'AcceptSelectionVSplit' => '<C-v>',
'Backspace' => '<BS>',
'Cancel' => ['<C-c>', '<Esc>'],
'Clear' => '<C-u>',
'CursorEnd' => '<C-e>',
'CursorLeft' => ['<Left>', '<C-h>'],
'CursorRight' => ['<Right>', '<C-l>'],
'CursorStart' => '<C-a>',
'Delete' => '<Del>',
'Refresh' => '<C-f>',
'SelectNext' => ['<C-n>', '<C-j>', '<Down>'],
'SelectPrev' => ['<C-p>', '<C-k>', '<Up>'],
'ToggleFocus' => '<Tab>',
}.each do |key, value|
if override = get_list_or_string("g:CommandT#{key}Map")
Array(override).each do |mapping|
map mapping, key
end
else
Array(value).each do |mapping|
unless mapping == '<Esc>' && term =~ /\A(screen|xterm|vt100)/
map mapping, key
end
end
end
end
end
# Returns the desired maximum number of matches, based on available
# vertical space and the g:CommandTMaxHeight option.
def match_limit
limit = VIM::Screen.lines - 5
limit = 1 if limit < 0
limit = [limit, max_height].min if max_height > 0
limit
end
def list_matches
matches = @active_finder.sorted_matches_for @prompt.abbrev, :limit => match_limit
@match_window.matches = matches
end
def buffer_finder
@buffer_finder ||= CommandT::BufferFinder.new
end
def file_finder
@file_finder ||= CommandT::FileFinder.new nil,
:max_depth => get_number('g:CommandTMaxDepth'),
:max_files => get_number('g:CommandTMaxFiles'),
:max_caches => get_number('g:CommandTMaxCachedDirectories'),
:always_show_dot_files => get_bool('g:CommandTAlwaysShowDotFiles'),
:never_show_dot_files => get_bool('g:CommandTNeverShowDotFiles'),
:scan_dot_directories => get_bool('g:CommandTScanDotDirectories')
end
def jump_finder
@jump_finder ||= CommandT::JumpFinder.new
end
def tag_finder
@tag_finder ||= CommandT::TagFinder.new \
:include_filenames => get_bool('g:CommandTTagIncludeFilenames')
end
end # class Controller
end # module commandT
| 30.263889 | 87 | 0.607526 |
081cda74bf936bf3b2228f3b18c29cfc0da7b4be | 6,604 | # frozen_string_literal: true
require 'spec_helper'
require_relative '../lib/cocoapods-pack/xcode_builder'
describe_with_private_methods XcodeBuilder do
let(:xcodebuild_opts) { nil }
subject do
ui = spy
XcodeBuilder.new('xcodeproject_path', xcodebuild_opts, 'xcodebuild_outdir', ui)
end
it 'breaks when giving a bad platform' do
expect { subject.build(:windows, 'target') }.to raise_error("Unknown platform: 'windows'")
end
it 'raises BuildError if shellout fails' do
expect { subject.build(:windows, 'target') }.to raise_error("Unknown platform: 'windows'")
end
it 'breaks with unknown type' do
builder = subject
mock_status = instance_double(Process::Status, success?: false, exitstatus: 42)
allow(builder).to receive(:warn)
allow(builder).to receive(:shellout).and_return(['error stderr', mock_status])
expected_error_message = "Failed to execute 'xcodebuild this will totally fail'. Exit status: 42"
expect { builder.run('xcodebuild this will totally fail') }.to raise_error(XcodeBuilder::BuildError, expected_error_message)
end
it 'executes xcodebuild in shell for osx' do
builder = subject
allow(builder).to receive(:run)
builder.build(:osx, 'PodsTarget')
expect(builder).to have_received(:run).with(%w[xcodebuild ONLY_ACTIVE_ARCH=NO SKIP_INSTALL=NO
BUILD_LIBRARY_FOR_DISTRIBUTION=YES
-project xcodeproject_path
-scheme "PodsTarget"
-configuration Release
EXCLUDED_SOURCE_FILE_NAMES=*-dummy.m
-destination "generic/platform=macOS"
archive
-archivePath xcodebuild_outdir/PodsTarget.xcarchive].join(' '))
end
it 'executes xcodebuild in shell for ios' do
builder = subject
allow(builder).to receive(:run)
builder.build(:ios, 'PodsTarget')
expect(builder).to have_received(:run).twice
expect(builder).to have_received(:run).with(%w[xcodebuild ONLY_ACTIVE_ARCH=NO SKIP_INSTALL=NO
BUILD_LIBRARY_FOR_DISTRIBUTION=YES
-project xcodeproject_path
-scheme "PodsTarget"
-configuration Release
EXCLUDED_SOURCE_FILE_NAMES=*-dummy.m
-destination "generic/platform=iOS Simulator"
archive
-archivePath xcodebuild_outdir/PodsTarget-simulator.xcarchive].join(' '))
expect(builder).to have_received(:run).with(%w[xcodebuild ONLY_ACTIVE_ARCH=NO SKIP_INSTALL=NO
BUILD_LIBRARY_FOR_DISTRIBUTION=YES
-project xcodeproject_path
-scheme "PodsTarget"
-configuration Release
EXCLUDED_SOURCE_FILE_NAMES=*-dummy.m
-destination "generic/platform=iOS"
archive
-archivePath xcodebuild_outdir/PodsTarget-device.xcarchive].join(' '))
end
it 'executes xcodebuild in shell for watchos' do
builder = subject
allow(builder).to receive(:run)
builder.build(:watchos, 'PodsTarget')
expect(builder).to have_received(:run).twice
expect(builder).to have_received(:run).with(%w[xcodebuild ONLY_ACTIVE_ARCH=NO SKIP_INSTALL=NO
BUILD_LIBRARY_FOR_DISTRIBUTION=YES
-project xcodeproject_path
-scheme "PodsTarget"
-configuration Release
EXCLUDED_SOURCE_FILE_NAMES=*-dummy.m
-destination "generic/platform=watchOS Simulator"
archive
-archivePath xcodebuild_outdir/PodsTarget-simulator.xcarchive].join(' '))
expect(builder).to have_received(:run).with(%w[xcodebuild ONLY_ACTIVE_ARCH=NO SKIP_INSTALL=NO
BUILD_LIBRARY_FOR_DISTRIBUTION=YES
-project xcodeproject_path
-scheme "PodsTarget"
-configuration Release
EXCLUDED_SOURCE_FILE_NAMES=*-dummy.m
-destination "generic/platform=watchOS"
archive
-archivePath xcodebuild_outdir/PodsTarget-device.xcarchive].join(' '))
end
context 'with non-nil xcodebuild_opts' do
let(:xcodebuild_opts) { 'CODE_SIGNING_REQUIRED=NO' }
it 'passes xcodebuild_opts to xcodebuild' do
allow(subject).to receive(:run)
subject.build(:osx, 'PodsTarget')
expect(subject).to have_received(:run).with(%w[xcodebuild ONLY_ACTIVE_ARCH=NO SKIP_INSTALL=NO
BUILD_LIBRARY_FOR_DISTRIBUTION=YES
-project xcodeproject_path
-scheme "PodsTarget"
-configuration Release
EXCLUDED_SOURCE_FILE_NAMES=*-dummy.m
-destination "generic/platform=macOS"
CODE_SIGNING_REQUIRED=NO
archive
-archivePath xcodebuild_outdir/PodsTarget.xcarchive].join(' '))
end
end
end
| 57.929825 | 128 | 0.482586 |
111834bbac6c319bcb4885425a4a4e21219affdc | 110 | class HomeController < ApplicationController
def index
u = User.find(1)
sign_in(:user, u)
end
end
| 15.714286 | 44 | 0.690909 |
21f2e3f6791a88c92944fea97a81850c91275ec5 | 2,302 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `rails
# db:schema:load`. When creating a new database, `rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2020_11_21_223306) do
create_table "active_storage_attachments", force: :cascade do |t|
t.string "name", null: false
t.string "record_type", null: false
t.integer "record_id", null: false
t.integer "blob_id", null: false
t.datetime "created_at", null: false
t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true
end
create_table "active_storage_blobs", force: :cascade do |t|
t.string "key", null: false
t.string "filename", null: false
t.string "content_type"
t.text "metadata"
t.bigint "byte_size", null: false
t.string "checksum", null: false
t.datetime "created_at", null: false
t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true
end
create_table "users", force: :cascade do |t|
t.string "username", default: "", null: false
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"
end
| 45.137255 | 126 | 0.735447 |
6aaf0288ff4f2ac2851789c14c25cfb8589a7449 | 4,898 | require 'manage_contacts'
def clear_contacts
path = File.expand_path('../lib/contacts.json', __dir__)
File.read(path)
empty_contacts = []
File.write(path, empty_contacts)
end
RSpec.describe ManageContacts do
before :each do
clear_contacts
@contact = ManageContacts.new
end
it 'creates a new instance of the Contact class' do
expect(@contact.is_a?(Object)).to eq(true)
end
it 'create_new_entry method creates new instance of Person and adds to @contacts' do
allow($stdin).to receive(:gets).and_return('Elle', 'H', '[email protected]', '07999999999')
allow('./lib/contacts.json').to receive(:write).with('first_name' => 'Elle', 'last_name' => 'H', 'email_address' => '[email protected]', 'phone_number' => '07999999999')
@contact.create_new_entry
expect(@contact.contacts).to eq([{ 'first_name' => 'Elle', 'last_name' => 'H', 'email_address' => '[email protected]', 'phone_number' => '07999999999' }])
end
end
RSpec.describe ManageContacts do
before :each do
clear_contacts
@contact = ManageContacts.new
allow($stdin).to receive(:gets).and_return('Elle', 'H', '[email protected]', '07999999999', 'Deneice', 'Daniels', '[email protected]', '07889999999', 'Amy', 'Winchester', '[email protected]', '07000000000')
@contact.create_new_entry
@contact.create_new_entry
@contact.create_new_entry
end
it 'returns contacts with the first name beginning with E only' do
contacts_beginning_e = @contact.search_first_name('E')
expect(contacts_beginning_e).to eq([{ 'first_name' => 'Elle', 'last_name' => 'H', 'email_address' => '[email protected]', 'phone_number' => '07999999999' }])
end
end
RSpec.describe ManageContacts do
before(:each) do
clear_contacts
@contact = ManageContacts.new
allow($stdin).to receive(:gets).and_return('Elle', 'Dorie', '[email protected]', '07999999999', 'Deneice', 'Smith', '[email protected]', '07989999999', 'Edward', 'Smith', '[email protected]', '07000000000')
@contact.create_new_entry
@contact.create_new_entry
@contact.create_new_entry
end
it 'displays contacts with last names beginning with Sm only. Results sorted by first name' do
last_name_sm = @contact.search_last_name('Sm')
expect(last_name_sm).to eq([{ 'first_name' => 'Deneice', 'last_name' => 'Smith', 'email_address' => '[email protected]', 'phone_number' => '07989999999' }, { 'first_name' => 'Edward', 'last_name' => 'Smith', 'email_address' => '[email protected]', 'phone_number' => '07000000000' }])
end
it "displays contacts with the email address beginning with 'E' only" do
email_address_e = @contact.search_email('E')
expect(email_address_e).to eq([{ 'first_name' => 'Edward', 'last_name' => 'Smith', 'email_address' => '[email protected]', 'phone_number' => '07000000000' }, { 'first_name' => 'Elle', 'last_name' => 'Dorie', 'email_address' => '[email protected]', 'phone_number' => '07999999999' }])
end
it "displays contacts with the phone number beginning with '079' only" do
phone_number = @contact.search_phone('079')
expect(phone_number).to eq([{ 'first_name' => 'Deneice', 'last_name' => 'Smith', 'email_address' => '[email protected]', 'phone_number' => '07989999999' }, { 'first_name' => 'Elle', 'last_name' => 'Dorie', 'email_address' => '[email protected]', 'phone_number' => '07999999999' }])
end
end
RSpec.describe ManageContacts do
before(:each) do
clear_contacts
@contact = ManageContacts.new
allow($stdin).to receive(:gets).and_return('Elle', 'Dorie', '[email protected]', '07999999999')
@contact.create_new_entry
end
it "creates a contact and then edits the first name to 'Eleanor'" do
allow($stdin).to receive(:gets).and_return('1', '1', 'Eleanor')
@contact.edit_contact
expect(@contact.contacts).to eq([{ 'first_name' => 'Eleanor', 'last_name' => 'Dorie', 'email_address' => '[email protected]', 'phone_number' => '07999999999' }])
end
it "creates a contact and then edits the last name to 'Hall'" do
allow($stdin).to receive(:gets).and_return('1', '2', 'Hall')
@contact.edit_contact
expect(@contact.contacts).to eq([{ 'first_name' => 'Elle', 'last_name' => 'Hall', 'email_address' => '[email protected]', 'phone_number' => '07999999999' }])
end
it "creates a contact and then edits the email address to '[email protected]'" do
allow($stdin).to receive(:gets).and_return('1', '3', '[email protected]')
@contact.edit_contact
expect(@contact.contacts).to eq([{ 'first_name' => 'Elle', 'last_name' => 'Dorie', 'email_address' => '[email protected]', 'phone_number' => '07999999999' }])
end
it "creates a contact and then edits the phone number to '07888999000'" do
allow($stdin).to receive(:gets).and_return('1', '4', '07888999000')
@contact.edit_contact
expect(@contact.contacts).to eq([{ 'first_name' => 'Elle', 'last_name' => 'Dorie', 'email_address' => '[email protected]', 'phone_number' => '07888999000' }])
end
end
| 48.019608 | 278 | 0.678032 |
ffaf22dbb3283bb6e54e2dd7b8ef98000e0fc184 | 22,711 | # frozen_string_literal: true
RSpec.describe "bundle clean" do
def should_have_gems(*gems)
gems.each do |g|
expect(vendored_gems("gems/#{g}")).to exist
expect(vendored_gems("specifications/#{g}.gemspec")).to exist
expect(vendored_gems("cache/#{g}.gem")).to exist
end
end
def should_not_have_gems(*gems)
gems.each do |g|
expect(vendored_gems("gems/#{g}")).not_to exist
expect(vendored_gems("specifications/#{g}.gemspec")).not_to exist
expect(vendored_gems("cache/#{g}.gem")).not_to exist
end
end
it "removes unused gems that are different" do
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "thin"
gem "foo"
G
bundle "config set path vendor/bundle"
bundle "config set clean false"
bundle "install"
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "thin"
G
bundle "install"
bundle :clean
expect(out).to include("Removing foo (1.0)")
should_have_gems "thin-1.0", "rack-1.0.0"
should_not_have_gems "foo-1.0"
expect(vendored_gems("bin/rackup")).to exist
end
it "removes old version of gem if unused" do
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack", "0.9.1"
gem "foo"
G
bundle "config set path vendor/bundle"
bundle "config set clean false"
bundle "install"
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack", "1.0.0"
gem "foo"
G
bundle "install"
bundle :clean
expect(out).to include("Removing rack (0.9.1)")
should_have_gems "foo-1.0", "rack-1.0.0"
should_not_have_gems "rack-0.9.1"
expect(vendored_gems("bin/rackup")).to exist
end
it "removes new version of gem if unused" do
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack", "1.0.0"
gem "foo"
G
bundle "config set path vendor/bundle"
bundle "config set clean false"
bundle "install"
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack", "0.9.1"
gem "foo"
G
bundle "update rack"
bundle :clean
expect(out).to include("Removing rack (1.0.0)")
should_have_gems "foo-1.0", "rack-0.9.1"
should_not_have_gems "rack-1.0.0"
expect(vendored_gems("bin/rackup")).to exist
end
it "removes gems in bundle without groups" do
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "foo"
group :test_group do
gem "rack", "1.0.0"
end
G
bundle "config set path vendor/bundle"
bundle "install"
bundle "config set without test_group"
bundle "install"
bundle :clean
expect(out).to include("Removing rack (1.0.0)")
should_have_gems "foo-1.0"
should_not_have_gems "rack-1.0.0"
expect(vendored_gems("bin/rackup")).to_not exist
end
it "does not remove cached git dir if it's being used" do
build_git "foo"
revision = revision_for(lib_path("foo-1.0"))
git_path = lib_path("foo-1.0")
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack", "1.0.0"
git "#{git_path}", :ref => "#{revision}" do
gem "foo"
end
G
bundle "config set path vendor/bundle"
bundle "install"
bundle :clean
digest = Digest(:SHA1).hexdigest(git_path.to_s)
cache_path = Bundler::VERSION.start_with?("2.") ? vendored_gems("cache/bundler/git/foo-1.0-#{digest}") : home(".bundle/cache/git/foo-1.0-#{digest}")
expect(cache_path).to exist
end
it "removes unused git gems" do
build_git "foo", :path => lib_path("foo")
git_path = lib_path("foo")
revision = revision_for(git_path)
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack", "1.0.0"
git "#{git_path}", :ref => "#{revision}" do
gem "foo"
end
G
bundle "config set path vendor/bundle"
bundle "install"
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack", "1.0.0"
G
bundle "install"
bundle :clean
expect(out).to include("Removing foo (#{revision[0..11]})")
expect(vendored_gems("gems/rack-1.0.0")).to exist
expect(vendored_gems("bundler/gems/foo-#{revision[0..11]}")).not_to exist
digest = Digest(:SHA1).hexdigest(git_path.to_s)
expect(vendored_gems("cache/bundler/git/foo-#{digest}")).not_to exist
expect(vendored_gems("specifications/rack-1.0.0.gemspec")).to exist
expect(vendored_gems("bin/rackup")).to exist
end
it "keeps used git gems even if installed to a symlinked location" do
build_git "foo", :path => lib_path("foo")
git_path = lib_path("foo")
revision = revision_for(git_path)
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack", "1.0.0"
git "#{git_path}", :ref => "#{revision}" do
gem "foo"
end
G
FileUtils.mkdir_p(bundled_app("real-path"))
FileUtils.ln_sf(bundled_app("real-path"), bundled_app("symlink-path"))
bundle "config set path #{bundled_app("symlink-path")}"
bundle "install"
bundle :clean
expect(out).not_to include("Removing foo (#{revision[0..11]})")
expect(bundled_app("symlink-path/#{Bundler.ruby_scope}/bundler/gems/foo-#{revision[0..11]}")).to exist
end
it "removes old git gems" do
build_git "foo-bar", :path => lib_path("foo-bar")
revision = revision_for(lib_path("foo-bar"))
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack", "1.0.0"
git "#{lib_path("foo-bar")}" do
gem "foo-bar"
end
G
bundle "config set path vendor/bundle"
bundle "install"
update_git "foo-bar", :path => lib_path("foo-bar")
revision2 = revision_for(lib_path("foo-bar"))
bundle "update", :all => true
bundle :clean
expect(out).to include("Removing foo-bar (#{revision[0..11]})")
expect(vendored_gems("gems/rack-1.0.0")).to exist
expect(vendored_gems("bundler/gems/foo-bar-#{revision[0..11]}")).not_to exist
expect(vendored_gems("bundler/gems/foo-bar-#{revision2[0..11]}")).to exist
expect(vendored_gems("specifications/rack-1.0.0.gemspec")).to exist
expect(vendored_gems("bin/rackup")).to exist
end
it "does not remove nested gems in a git repo" do
build_lib "activesupport", "3.0", :path => lib_path("rails/activesupport")
build_git "rails", "3.0", :path => lib_path("rails") do |s|
s.add_dependency "activesupport", "= 3.0"
end
revision = revision_for(lib_path("rails"))
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "activesupport", :git => "#{lib_path("rails")}", :ref => '#{revision}'
G
bundle "config set path vendor/bundle"
bundle "install"
bundle :clean
expect(out).to include("")
expect(vendored_gems("bundler/gems/rails-#{revision[0..11]}")).to exist
end
it "does not remove git sources that are in without groups" do
build_git "foo", :path => lib_path("foo")
git_path = lib_path("foo")
revision = revision_for(git_path)
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack", "1.0.0"
group :test do
git "#{git_path}", :ref => "#{revision}" do
gem "foo"
end
end
G
bundle "config set path vendor/bundle"
bundle "config set without test"
bundle "install"
bundle :clean
expect(out).to include("")
expect(vendored_gems("bundler/gems/foo-#{revision[0..11]}")).to exist
digest = Digest(:SHA1).hexdigest(git_path.to_s)
expect(vendored_gems("cache/bundler/git/foo-#{digest}")).to_not exist
end
it "does not blow up when using without groups" do
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack"
group :development do
gem "foo"
end
G
bundle "config set path vendor/bundle"
bundle "config set without development"
bundle "install"
bundle :clean
end
it "displays an error when used without --path" do
bundle "config set path.system true"
install_gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack", "1.0.0"
G
bundle :clean, :raise_on_error => false
expect(exitstatus).to eq(15)
expect(err).to include("--force")
end
# handling bundle clean upgrade path from the pre's
it "removes .gem/.gemspec file even if there's no corresponding gem dir" do
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "thin"
gem "foo"
G
bundle "config set path vendor/bundle"
bundle "install"
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "foo"
G
bundle "install"
FileUtils.rm(vendored_gems("bin/rackup"))
FileUtils.rm_rf(vendored_gems("gems/thin-1.0"))
FileUtils.rm_rf(vendored_gems("gems/rack-1.0.0"))
bundle :clean
should_not_have_gems "thin-1.0", "rack-1.0"
should_have_gems "foo-1.0"
expect(vendored_gems("bin/rackup")).not_to exist
end
it "does not call clean automatically when using system gems" do
bundle "config set path.system true"
install_gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "thin"
gem "rack"
G
install_gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack"
G
gem_command :list
expect(out).to include("rack (1.0.0)").and include("thin (1.0)")
end
it "--clean should override the bundle setting on install", :bundler => "< 3" do
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "thin"
gem "rack"
G
bundle "config set path vendor/bundle"
bundle "config set clean false"
bundle "install --clean true"
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack"
G
bundle "install"
should_have_gems "rack-1.0.0"
should_not_have_gems "thin-1.0"
end
it "--clean should override the bundle setting on update", :bundler => "< 3" do
build_repo2
gemfile <<-G
source "#{file_uri_for(gem_repo2)}"
gem "foo"
G
bundle "config set path vendor/bundle"
bundle "config set clean false"
bundle "install --clean true"
update_repo2 do
build_gem "foo", "1.0.1"
end
bundle "update", :all => true
should_have_gems "foo-1.0.1"
should_not_have_gems "foo-1.0"
end
it "automatically cleans when path has not been set", :bundler => "3" do
build_repo2
install_gemfile <<-G
source "#{file_uri_for(gem_repo2)}"
gem "foo"
G
update_repo2 do
build_gem "foo", "1.0.1"
end
bundle "update", :all => true
files = Pathname.glob(bundled_app(".bundle", Bundler.ruby_scope, "*", "*"))
files.map! {|f| f.to_s.sub(bundled_app(".bundle", Bundler.ruby_scope).to_s, "") }
expect(files.sort).to eq %w[
/cache/foo-1.0.1.gem
/gems/foo-1.0.1
/specifications/foo-1.0.1.gemspec
]
end
it "does not clean automatically on --path" do
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "thin"
gem "rack"
G
bundle "config set path vendor/bundle"
bundle "install"
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack"
G
bundle "install"
should_have_gems "rack-1.0.0", "thin-1.0"
end
it "does not clean on bundle update with --path" do
build_repo2
gemfile <<-G
source "#{file_uri_for(gem_repo2)}"
gem "foo"
G
bundle "config set path vendor/bundle"
bundle "install"
update_repo2 do
build_gem "foo", "1.0.1"
end
bundle :update, :all => true
should_have_gems "foo-1.0", "foo-1.0.1"
end
it "does not clean on bundle update when using --system" do
bundle "config set path.system true"
build_repo2
gemfile <<-G
source "#{file_uri_for(gem_repo2)}"
gem "foo"
G
bundle "install"
update_repo2 do
build_gem "foo", "1.0.1"
end
bundle :update, :all => true
gem_command :list
expect(out).to include("foo (1.0.1, 1.0)")
end
it "cleans system gems when --force is used" do
bundle "config set path.system true"
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "foo"
gem "rack"
G
bundle :install
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack"
G
bundle :install
bundle "clean --force"
expect(out).to include("Removing foo (1.0)")
gem_command :list
expect(out).not_to include("foo (1.0)")
expect(out).to include("rack (1.0.0)")
end
describe "when missing permissions", :permissions do
before { ENV["BUNDLE_PATH__SYSTEM"] = "true" }
let(:system_cache_path) { system_gem_path("cache") }
after do
FileUtils.chmod(0o755, system_cache_path)
end
it "returns a helpful error message" do
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "foo"
gem "rack"
G
bundle :install
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack"
G
bundle :install
FileUtils.chmod(0o500, system_cache_path)
bundle :clean, :force => true, :raise_on_error => false
expect(err).to include(system_gem_path.to_s)
expect(err).to include("grant write permissions")
gem_command :list
expect(out).to include("foo (1.0)")
expect(out).to include("rack (1.0.0)")
end
end
it "cleans git gems with a 7 length git revision" do
build_git "foo"
revision = revision_for(lib_path("foo-1.0"))
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "foo", :git => "#{lib_path("foo-1.0")}"
G
bundle "config set path vendor/bundle"
bundle "install"
# mimic 7 length git revisions in Gemfile.lock
gemfile_lock = File.read(bundled_app_lock).split("\n")
gemfile_lock.each_with_index do |line, index|
gemfile_lock[index] = line[0..(11 + 7)] if line.include?(" revision:")
end
lockfile(bundled_app_lock, gemfile_lock.join("\n"))
bundle "config set path vendor/bundle"
bundle "install"
bundle :clean
expect(out).not_to include("Removing foo (1.0 #{revision[0..6]})")
expect(vendored_gems("bundler/gems/foo-1.0-#{revision[0..6]}")).to exist
end
it "when using --force on system gems, it doesn't remove binaries" do
bundle "config set path.system true"
build_repo2 do
build_gem "bindir" do |s|
s.bindir = "exe"
s.executables = "foo"
end
end
gemfile <<-G
source "#{file_uri_for(gem_repo2)}"
gem "bindir"
G
bundle :install
bundle "clean --force"
sys_exec "foo"
expect(out).to eq("1.0")
end
it "when using --force, it doesn't remove default gem binaries" do
skip "does not work on old rubies because the realworld gems that need to be installed don't support them" if RUBY_VERSION < "2.7.0"
skip "does not work on rubygems versions where `--install_dir` doesn't respect --default" unless Gem::Installer.for_spec(loaded_gemspec, :install_dir => "/foo").default_spec_file == "/foo/specifications/default/bundler-#{Bundler::VERSION}.gemspec" # Since rubygems 3.2.0.rc.2
default_irb_version = ruby "gem 'irb', '< 999999'; require 'irb'; puts IRB::VERSION", :raise_on_error => false
skip "irb isn't a default gem" if default_irb_version.empty?
# simulate executable for default gem
build_gem "irb", default_irb_version, :to_system => true, :default => true do |s|
s.executables = "irb"
end
realworld_system_gems "fiddle --version 1.0.6", "tsort --version 0.1.0", "pathname --version 0.1.0", "set --version 1.0.1"
install_gemfile <<-G
source "#{file_uri_for(gem_repo2)}"
G
bundle "clean --force", :env => { "BUNDLER_GEM_DEFAULT_DIR" => system_gem_path.to_s }
expect(out).not_to include("Removing irb")
end
it "doesn't blow up on path gems without a .gemspec" do
relative_path = "vendor/private_gems/bar-1.0"
absolute_path = bundled_app(relative_path)
FileUtils.mkdir_p("#{absolute_path}/lib/bar")
File.open("#{absolute_path}/lib/bar/bar.rb", "wb") do |file|
file.puts "module Bar; end"
end
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "foo"
gem "bar", "1.0", :path => "#{relative_path}"
G
bundle "config set path vendor/bundle"
bundle "install"
bundle :clean
end
it "doesn't remove gems in dry-run mode with path set" do
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "thin"
gem "foo"
G
bundle "config set path vendor/bundle"
bundle "config set clean false"
bundle "install"
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "thin"
G
bundle :install
bundle "clean --dry-run"
expect(out).not_to include("Removing foo (1.0)")
expect(out).to include("Would have removed foo (1.0)")
should_have_gems "thin-1.0", "rack-1.0.0", "foo-1.0"
expect(vendored_gems("bin/rackup")).to exist
end
it "doesn't remove gems in dry-run mode with no path set" do
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "thin"
gem "foo"
G
bundle "config set path vendor/bundle"
bundle "config set clean false"
bundle "install"
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "thin"
G
bundle :install
bundle "clean --dry-run"
expect(out).not_to include("Removing foo (1.0)")
expect(out).to include("Would have removed foo (1.0)")
should_have_gems "thin-1.0", "rack-1.0.0", "foo-1.0"
expect(vendored_gems("bin/rackup")).to exist
end
it "doesn't store dry run as a config setting" do
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "thin"
gem "foo"
G
bundle "config set path vendor/bundle"
bundle "config set clean false"
bundle "install"
bundle "config set dry_run false"
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "thin"
G
bundle :install
bundle "clean"
expect(out).to include("Removing foo (1.0)")
expect(out).not_to include("Would have removed foo (1.0)")
should_have_gems "thin-1.0", "rack-1.0.0"
should_not_have_gems "foo-1.0"
expect(vendored_gems("bin/rackup")).to exist
end
it "performs an automatic bundle install" do
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "thin"
gem "foo"
G
bundle "config set path vendor/bundle"
bundle "config set clean false"
bundle "install"
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "thin"
gem "weakling"
G
bundle "config set auto_install 1"
bundle :clean
expect(out).to include("Installing weakling 0.0.3")
should_have_gems "thin-1.0", "rack-1.0.0", "weakling-0.0.3"
should_not_have_gems "foo-1.0"
end
it "doesn't remove extensions artifacts from bundled git gems after clean", :ruby_repo do
build_git "very_simple_git_binary", &:add_c_extension
revision = revision_for(lib_path("very_simple_git_binary-1.0"))
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "very_simple_git_binary", :git => "#{lib_path("very_simple_git_binary-1.0")}", :ref => "#{revision}"
G
bundle "config set path vendor/bundle"
bundle "install"
expect(vendored_gems("bundler/gems/extensions")).to exist
expect(vendored_gems("bundler/gems/very_simple_git_binary-1.0-#{revision[0..11]}")).to exist
bundle :clean
expect(out).to be_empty
expect(vendored_gems("bundler/gems/extensions")).to exist
expect(vendored_gems("bundler/gems/very_simple_git_binary-1.0-#{revision[0..11]}")).to exist
end
it "removes extension directories", :ruby_repo do
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "thin"
gem "very_simple_binary"
gem "simple_binary"
G
bundle "config set path vendor/bundle"
bundle "install"
very_simple_binary_extensions_dir =
Pathname.glob("#{vendored_gems}/extensions/*/*/very_simple_binary-1.0").first
simple_binary_extensions_dir =
Pathname.glob("#{vendored_gems}/extensions/*/*/simple_binary-1.0").first
expect(very_simple_binary_extensions_dir).to exist
expect(simple_binary_extensions_dir).to exist
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "thin"
gem "simple_binary"
G
bundle "install"
bundle :clean
expect(out).to eq("Removing very_simple_binary (1.0)")
expect(very_simple_binary_extensions_dir).not_to exist
expect(simple_binary_extensions_dir).to exist
end
it "removes git extension directories", :ruby_repo do
build_git "very_simple_git_binary", &:add_c_extension
revision = revision_for(lib_path("very_simple_git_binary-1.0"))
short_revision = revision[0..11]
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "thin"
gem "very_simple_git_binary", :git => "#{lib_path("very_simple_git_binary-1.0")}", :ref => "#{revision}"
G
bundle "config set path vendor/bundle"
bundle "install"
very_simple_binary_extensions_dir =
Pathname.glob("#{vendored_gems}/bundler/gems/extensions/*/*/very_simple_git_binary-1.0-#{short_revision}").first
expect(very_simple_binary_extensions_dir).to exist
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "very_simple_git_binary", :git => "#{lib_path("very_simple_git_binary-1.0")}", :ref => "#{revision}"
G
bundle "install"
bundle :clean
expect(out).to include("Removing thin (1.0)")
expect(very_simple_binary_extensions_dir).to exist
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
G
bundle "install"
bundle :clean
expect(out).to eq("Removing very_simple_git_binary-1.0 (#{short_revision})")
expect(very_simple_binary_extensions_dir).not_to exist
end
it "keeps git extension directories when excluded by group" do
build_git "very_simple_git_binary", &:add_c_extension
revision = revision_for(lib_path("very_simple_git_binary-1.0"))
short_revision = revision[0..11]
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
group :development do
gem "very_simple_git_binary", :git => "#{lib_path("very_simple_git_binary-1.0")}", :ref => "#{revision}"
end
G
bundle :lock
bundle "config set without development"
bundle "config set path vendor/bundle"
bundle "install"
bundle :clean
very_simple_binary_extensions_dir =
Pathname.glob("#{vendored_gems}/bundler/gems/extensions/*/*/very_simple_git_binary-1.0-#{short_revision}").first
expect(very_simple_binary_extensions_dir).to be_nil
end
end
| 24.76663 | 279 | 0.634979 |
bf42a55e3bf30d62667aee3e875a7555cd5ea4a4 | 1,809 | # frozen_string_literal: true
module Meals
# Handles meal imports.
class ImportsController < ApplicationController
before_action :authorize_import
before_action -> { nav_context(:meals, :meals) }
def show
@import = Import.find(params[:id])
prep_form_vars
return unless request.xhr?
if @import.complete?
render(partial: "results")
else
head(:no_content)
end
end
def new
prep_form_vars
end
def create
@new_import = Import.create(import_params.merge(community: current_community, user: current_user))
if @new_import.valid?
ImportJob.perform_later(class_name: "Meals::Import", id: @new_import.id)
redirect_to(meals_import_path(@new_import))
else
prep_form_vars
render(:new)
end
end
private
def prep_form_vars
@new_import ||= Import.new
@roles = Meals::Role.in_community(current_community).by_title
@sample_times = [Time.current.midnight + 7.days, Time.current.midnight + 10.days].map do |t|
(t + 18.hours).to_s(:no_sec_no_t)
end
@locations = Meal.hosted_by(current_community).newest_first.first&.calendars
@locations ||= Calendars::Calendar.in_community(current_community).meal_hostable[0...2].presence
@locations ||= [
Calendars::Calendar.new(id: 1234, name: "Dining Room"),
Calendars::Calendar.new(id: 5678, name: "Kitchen")
]
@formula = Formula.default_for(current_community) || Formula.new(id: 439, name: "Main Formula")
end
def authorize_import
authorize(Meal.new(community: current_community), :import?, policy_class: Meals::MealPolicy)
end
def import_params
params.require(:meals_import).permit(:file_new_signed_id)
end
end
end
| 29.655738 | 104 | 0.667772 |
bf73ffd22e6f222f3b88c7a91842aa0401a6d269 | 2,343 | # This file has been automatically generated from a template file.
# Please make modifications to `templates/gRPC.podspec.template`
# instead. This file can be regenerated from the template by running
# `tools/buildgen/generate_projects.sh`.
# Copyright 2015 gRPC authors.
#
# 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.
Pod::Spec.new do |s|
s.name = 'gRPC'
version = '1.12.0-dev'
s.version = version
s.summary = 'gRPC client library for iOS/OSX'
s.homepage = 'https://grpc.io'
s.license = 'Apache License, Version 2.0'
s.authors = { 'The gRPC contributors' => '[email protected]' }
s.source = {
:git => 'https://github.com/grpc/grpc.git',
:tag => "v#{version}",
}
s.ios.deployment_target = '7.0'
s.osx.deployment_target = '10.9'
name = 'GRPCClient'
s.module_name = name
s.header_dir = name
src_dir = 'src/objective-c/GRPCClient'
s.dependency 'gRPC-RxLibrary', version
s.default_subspec = 'Main'
# Certificates, to be able to establish TLS connections:
s.resource_bundles = { 'gRPCCertificates' => ['etc/roots.pem'] }
s.pod_target_xcconfig = {
# This is needed by all pods that depend on gRPC-RxLibrary:
'CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES' => 'YES',
'CLANG_WARN_STRICT_PROTOTYPES' => 'NO',
}
s.subspec 'Main' do |ss|
ss.header_mappings_dir = "#{src_dir}"
ss.source_files = "#{src_dir}/*.{h,m}", "#{src_dir}/**/*.{h,m}"
ss.exclude_files = "#{src_dir}/GRPCCall+GID.{h,m}"
ss.private_header_files = "#{src_dir}/private/*.h"
ss.dependency 'gRPC-Core', version
end
s.subspec 'GID' do |ss|
ss.ios.deployment_target = '7.0'
ss.header_mappings_dir = "#{src_dir}"
ss.source_files = "#{src_dir}/GRPCCall+GID.{h,m}"
ss.dependency "#{s.name}/Main", version
ss.dependency 'Google/SignIn'
end
end
| 30.428571 | 74 | 0.68886 |
61b75e14fcddf55e52dca7bf0e8975d64dce4931 | 21,971 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/videointelligence/v1/video_intelligence.proto
require 'google/api/annotations_pb'
require 'google/api/client_pb'
require 'google/api/field_behavior_pb'
require 'google/longrunning/operations_pb'
require 'google/protobuf/duration_pb'
require 'google/protobuf/timestamp_pb'
require 'google/rpc/status_pb'
require 'google/protobuf'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_file("google/cloud/videointelligence/v1/video_intelligence.proto", :syntax => :proto3) do
add_message "google.cloud.videointelligence.v1.AnnotateVideoRequest" do
optional :input_uri, :string, 1
optional :input_content, :bytes, 6
repeated :features, :enum, 2, "google.cloud.videointelligence.v1.Feature"
optional :video_context, :message, 3, "google.cloud.videointelligence.v1.VideoContext"
optional :output_uri, :string, 4
optional :location_id, :string, 5
end
add_message "google.cloud.videointelligence.v1.VideoContext" do
repeated :segments, :message, 1, "google.cloud.videointelligence.v1.VideoSegment"
optional :label_detection_config, :message, 2, "google.cloud.videointelligence.v1.LabelDetectionConfig"
optional :shot_change_detection_config, :message, 3, "google.cloud.videointelligence.v1.ShotChangeDetectionConfig"
optional :explicit_content_detection_config, :message, 4, "google.cloud.videointelligence.v1.ExplicitContentDetectionConfig"
optional :face_detection_config, :message, 5, "google.cloud.videointelligence.v1.FaceDetectionConfig"
optional :speech_transcription_config, :message, 6, "google.cloud.videointelligence.v1.SpeechTranscriptionConfig"
optional :text_detection_config, :message, 8, "google.cloud.videointelligence.v1.TextDetectionConfig"
optional :person_detection_config, :message, 11, "google.cloud.videointelligence.v1.PersonDetectionConfig"
optional :object_tracking_config, :message, 13, "google.cloud.videointelligence.v1.ObjectTrackingConfig"
end
add_message "google.cloud.videointelligence.v1.LabelDetectionConfig" do
optional :label_detection_mode, :enum, 1, "google.cloud.videointelligence.v1.LabelDetectionMode"
optional :stationary_camera, :bool, 2
optional :model, :string, 3
optional :frame_confidence_threshold, :float, 4
optional :video_confidence_threshold, :float, 5
end
add_message "google.cloud.videointelligence.v1.ShotChangeDetectionConfig" do
optional :model, :string, 1
end
add_message "google.cloud.videointelligence.v1.ObjectTrackingConfig" do
optional :model, :string, 1
end
add_message "google.cloud.videointelligence.v1.FaceDetectionConfig" do
optional :model, :string, 1
optional :include_bounding_boxes, :bool, 2
optional :include_attributes, :bool, 5
end
add_message "google.cloud.videointelligence.v1.PersonDetectionConfig" do
optional :include_bounding_boxes, :bool, 1
optional :include_pose_landmarks, :bool, 2
optional :include_attributes, :bool, 3
end
add_message "google.cloud.videointelligence.v1.ExplicitContentDetectionConfig" do
optional :model, :string, 1
end
add_message "google.cloud.videointelligence.v1.TextDetectionConfig" do
repeated :language_hints, :string, 1
optional :model, :string, 2
end
add_message "google.cloud.videointelligence.v1.VideoSegment" do
optional :start_time_offset, :message, 1, "google.protobuf.Duration"
optional :end_time_offset, :message, 2, "google.protobuf.Duration"
end
add_message "google.cloud.videointelligence.v1.LabelSegment" do
optional :segment, :message, 1, "google.cloud.videointelligence.v1.VideoSegment"
optional :confidence, :float, 2
end
add_message "google.cloud.videointelligence.v1.LabelFrame" do
optional :time_offset, :message, 1, "google.protobuf.Duration"
optional :confidence, :float, 2
end
add_message "google.cloud.videointelligence.v1.Entity" do
optional :entity_id, :string, 1
optional :description, :string, 2
optional :language_code, :string, 3
end
add_message "google.cloud.videointelligence.v1.LabelAnnotation" do
optional :entity, :message, 1, "google.cloud.videointelligence.v1.Entity"
repeated :category_entities, :message, 2, "google.cloud.videointelligence.v1.Entity"
repeated :segments, :message, 3, "google.cloud.videointelligence.v1.LabelSegment"
repeated :frames, :message, 4, "google.cloud.videointelligence.v1.LabelFrame"
optional :version, :string, 5
end
add_message "google.cloud.videointelligence.v1.ExplicitContentFrame" do
optional :time_offset, :message, 1, "google.protobuf.Duration"
optional :pornography_likelihood, :enum, 2, "google.cloud.videointelligence.v1.Likelihood"
end
add_message "google.cloud.videointelligence.v1.ExplicitContentAnnotation" do
repeated :frames, :message, 1, "google.cloud.videointelligence.v1.ExplicitContentFrame"
optional :version, :string, 2
end
add_message "google.cloud.videointelligence.v1.NormalizedBoundingBox" do
optional :left, :float, 1
optional :top, :float, 2
optional :right, :float, 3
optional :bottom, :float, 4
end
add_message "google.cloud.videointelligence.v1.FaceDetectionAnnotation" do
repeated :tracks, :message, 3, "google.cloud.videointelligence.v1.Track"
optional :thumbnail, :bytes, 4
optional :version, :string, 5
end
add_message "google.cloud.videointelligence.v1.PersonDetectionAnnotation" do
repeated :tracks, :message, 1, "google.cloud.videointelligence.v1.Track"
optional :version, :string, 2
end
add_message "google.cloud.videointelligence.v1.FaceSegment" do
optional :segment, :message, 1, "google.cloud.videointelligence.v1.VideoSegment"
end
add_message "google.cloud.videointelligence.v1.FaceFrame" do
repeated :normalized_bounding_boxes, :message, 1, "google.cloud.videointelligence.v1.NormalizedBoundingBox"
optional :time_offset, :message, 2, "google.protobuf.Duration"
end
add_message "google.cloud.videointelligence.v1.FaceAnnotation" do
optional :thumbnail, :bytes, 1
repeated :segments, :message, 2, "google.cloud.videointelligence.v1.FaceSegment"
repeated :frames, :message, 3, "google.cloud.videointelligence.v1.FaceFrame"
end
add_message "google.cloud.videointelligence.v1.TimestampedObject" do
optional :normalized_bounding_box, :message, 1, "google.cloud.videointelligence.v1.NormalizedBoundingBox"
optional :time_offset, :message, 2, "google.protobuf.Duration"
repeated :attributes, :message, 3, "google.cloud.videointelligence.v1.DetectedAttribute"
repeated :landmarks, :message, 4, "google.cloud.videointelligence.v1.DetectedLandmark"
end
add_message "google.cloud.videointelligence.v1.Track" do
optional :segment, :message, 1, "google.cloud.videointelligence.v1.VideoSegment"
repeated :timestamped_objects, :message, 2, "google.cloud.videointelligence.v1.TimestampedObject"
repeated :attributes, :message, 3, "google.cloud.videointelligence.v1.DetectedAttribute"
optional :confidence, :float, 4
end
add_message "google.cloud.videointelligence.v1.DetectedAttribute" do
optional :name, :string, 1
optional :confidence, :float, 2
optional :value, :string, 3
end
add_message "google.cloud.videointelligence.v1.DetectedLandmark" do
optional :name, :string, 1
optional :point, :message, 2, "google.cloud.videointelligence.v1.NormalizedVertex"
optional :confidence, :float, 3
end
add_message "google.cloud.videointelligence.v1.VideoAnnotationResults" do
optional :input_uri, :string, 1
optional :segment, :message, 10, "google.cloud.videointelligence.v1.VideoSegment"
repeated :segment_label_annotations, :message, 2, "google.cloud.videointelligence.v1.LabelAnnotation"
repeated :segment_presence_label_annotations, :message, 23, "google.cloud.videointelligence.v1.LabelAnnotation"
repeated :shot_label_annotations, :message, 3, "google.cloud.videointelligence.v1.LabelAnnotation"
repeated :shot_presence_label_annotations, :message, 24, "google.cloud.videointelligence.v1.LabelAnnotation"
repeated :frame_label_annotations, :message, 4, "google.cloud.videointelligence.v1.LabelAnnotation"
repeated :face_annotations, :message, 5, "google.cloud.videointelligence.v1.FaceAnnotation"
repeated :face_detection_annotations, :message, 13, "google.cloud.videointelligence.v1.FaceDetectionAnnotation"
repeated :shot_annotations, :message, 6, "google.cloud.videointelligence.v1.VideoSegment"
optional :explicit_annotation, :message, 7, "google.cloud.videointelligence.v1.ExplicitContentAnnotation"
repeated :speech_transcriptions, :message, 11, "google.cloud.videointelligence.v1.SpeechTranscription"
repeated :text_annotations, :message, 12, "google.cloud.videointelligence.v1.TextAnnotation"
repeated :object_annotations, :message, 14, "google.cloud.videointelligence.v1.ObjectTrackingAnnotation"
repeated :logo_recognition_annotations, :message, 19, "google.cloud.videointelligence.v1.LogoRecognitionAnnotation"
repeated :person_detection_annotations, :message, 20, "google.cloud.videointelligence.v1.PersonDetectionAnnotation"
optional :error, :message, 9, "google.rpc.Status"
end
add_message "google.cloud.videointelligence.v1.AnnotateVideoResponse" do
repeated :annotation_results, :message, 1, "google.cloud.videointelligence.v1.VideoAnnotationResults"
end
add_message "google.cloud.videointelligence.v1.VideoAnnotationProgress" do
optional :input_uri, :string, 1
optional :progress_percent, :int32, 2
optional :start_time, :message, 3, "google.protobuf.Timestamp"
optional :update_time, :message, 4, "google.protobuf.Timestamp"
optional :feature, :enum, 5, "google.cloud.videointelligence.v1.Feature"
optional :segment, :message, 6, "google.cloud.videointelligence.v1.VideoSegment"
end
add_message "google.cloud.videointelligence.v1.AnnotateVideoProgress" do
repeated :annotation_progress, :message, 1, "google.cloud.videointelligence.v1.VideoAnnotationProgress"
end
add_message "google.cloud.videointelligence.v1.SpeechTranscriptionConfig" do
optional :language_code, :string, 1
optional :max_alternatives, :int32, 2
optional :filter_profanity, :bool, 3
repeated :speech_contexts, :message, 4, "google.cloud.videointelligence.v1.SpeechContext"
optional :enable_automatic_punctuation, :bool, 5
repeated :audio_tracks, :int32, 6
optional :enable_speaker_diarization, :bool, 7
optional :diarization_speaker_count, :int32, 8
optional :enable_word_confidence, :bool, 9
end
add_message "google.cloud.videointelligence.v1.SpeechContext" do
repeated :phrases, :string, 1
end
add_message "google.cloud.videointelligence.v1.SpeechTranscription" do
repeated :alternatives, :message, 1, "google.cloud.videointelligence.v1.SpeechRecognitionAlternative"
optional :language_code, :string, 2
end
add_message "google.cloud.videointelligence.v1.SpeechRecognitionAlternative" do
optional :transcript, :string, 1
optional :confidence, :float, 2
repeated :words, :message, 3, "google.cloud.videointelligence.v1.WordInfo"
end
add_message "google.cloud.videointelligence.v1.WordInfo" do
optional :start_time, :message, 1, "google.protobuf.Duration"
optional :end_time, :message, 2, "google.protobuf.Duration"
optional :word, :string, 3
optional :confidence, :float, 4
optional :speaker_tag, :int32, 5
end
add_message "google.cloud.videointelligence.v1.NormalizedVertex" do
optional :x, :float, 1
optional :y, :float, 2
end
add_message "google.cloud.videointelligence.v1.NormalizedBoundingPoly" do
repeated :vertices, :message, 1, "google.cloud.videointelligence.v1.NormalizedVertex"
end
add_message "google.cloud.videointelligence.v1.TextSegment" do
optional :segment, :message, 1, "google.cloud.videointelligence.v1.VideoSegment"
optional :confidence, :float, 2
repeated :frames, :message, 3, "google.cloud.videointelligence.v1.TextFrame"
end
add_message "google.cloud.videointelligence.v1.TextFrame" do
optional :rotated_bounding_box, :message, 1, "google.cloud.videointelligence.v1.NormalizedBoundingPoly"
optional :time_offset, :message, 2, "google.protobuf.Duration"
end
add_message "google.cloud.videointelligence.v1.TextAnnotation" do
optional :text, :string, 1
repeated :segments, :message, 2, "google.cloud.videointelligence.v1.TextSegment"
optional :version, :string, 3
end
add_message "google.cloud.videointelligence.v1.ObjectTrackingFrame" do
optional :normalized_bounding_box, :message, 1, "google.cloud.videointelligence.v1.NormalizedBoundingBox"
optional :time_offset, :message, 2, "google.protobuf.Duration"
end
add_message "google.cloud.videointelligence.v1.ObjectTrackingAnnotation" do
optional :entity, :message, 1, "google.cloud.videointelligence.v1.Entity"
optional :confidence, :float, 4
repeated :frames, :message, 2, "google.cloud.videointelligence.v1.ObjectTrackingFrame"
optional :version, :string, 6
oneof :track_info do
optional :segment, :message, 3, "google.cloud.videointelligence.v1.VideoSegment"
optional :track_id, :int64, 5
end
end
add_message "google.cloud.videointelligence.v1.LogoRecognitionAnnotation" do
optional :entity, :message, 1, "google.cloud.videointelligence.v1.Entity"
repeated :tracks, :message, 2, "google.cloud.videointelligence.v1.Track"
repeated :segments, :message, 3, "google.cloud.videointelligence.v1.VideoSegment"
end
add_enum "google.cloud.videointelligence.v1.Feature" do
value :FEATURE_UNSPECIFIED, 0
value :LABEL_DETECTION, 1
value :SHOT_CHANGE_DETECTION, 2
value :EXPLICIT_CONTENT_DETECTION, 3
value :FACE_DETECTION, 4
value :SPEECH_TRANSCRIPTION, 6
value :TEXT_DETECTION, 7
value :OBJECT_TRACKING, 9
value :LOGO_RECOGNITION, 12
value :PERSON_DETECTION, 14
end
add_enum "google.cloud.videointelligence.v1.LabelDetectionMode" do
value :LABEL_DETECTION_MODE_UNSPECIFIED, 0
value :SHOT_MODE, 1
value :FRAME_MODE, 2
value :SHOT_AND_FRAME_MODE, 3
end
add_enum "google.cloud.videointelligence.v1.Likelihood" do
value :LIKELIHOOD_UNSPECIFIED, 0
value :VERY_UNLIKELY, 1
value :UNLIKELY, 2
value :POSSIBLE, 3
value :LIKELY, 4
value :VERY_LIKELY, 5
end
end
end
module Google
module Cloud
module VideoIntelligence
module V1
AnnotateVideoRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.AnnotateVideoRequest").msgclass
VideoContext = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.VideoContext").msgclass
LabelDetectionConfig = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.LabelDetectionConfig").msgclass
ShotChangeDetectionConfig = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.ShotChangeDetectionConfig").msgclass
ObjectTrackingConfig = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.ObjectTrackingConfig").msgclass
FaceDetectionConfig = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.FaceDetectionConfig").msgclass
PersonDetectionConfig = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.PersonDetectionConfig").msgclass
ExplicitContentDetectionConfig = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.ExplicitContentDetectionConfig").msgclass
TextDetectionConfig = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.TextDetectionConfig").msgclass
VideoSegment = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.VideoSegment").msgclass
LabelSegment = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.LabelSegment").msgclass
LabelFrame = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.LabelFrame").msgclass
Entity = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.Entity").msgclass
LabelAnnotation = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.LabelAnnotation").msgclass
ExplicitContentFrame = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.ExplicitContentFrame").msgclass
ExplicitContentAnnotation = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.ExplicitContentAnnotation").msgclass
NormalizedBoundingBox = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.NormalizedBoundingBox").msgclass
FaceDetectionAnnotation = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.FaceDetectionAnnotation").msgclass
PersonDetectionAnnotation = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.PersonDetectionAnnotation").msgclass
FaceSegment = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.FaceSegment").msgclass
FaceFrame = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.FaceFrame").msgclass
FaceAnnotation = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.FaceAnnotation").msgclass
TimestampedObject = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.TimestampedObject").msgclass
Track = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.Track").msgclass
DetectedAttribute = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.DetectedAttribute").msgclass
DetectedLandmark = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.DetectedLandmark").msgclass
VideoAnnotationResults = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.VideoAnnotationResults").msgclass
AnnotateVideoResponse = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.AnnotateVideoResponse").msgclass
VideoAnnotationProgress = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.VideoAnnotationProgress").msgclass
AnnotateVideoProgress = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.AnnotateVideoProgress").msgclass
SpeechTranscriptionConfig = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.SpeechTranscriptionConfig").msgclass
SpeechContext = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.SpeechContext").msgclass
SpeechTranscription = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.SpeechTranscription").msgclass
SpeechRecognitionAlternative = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.SpeechRecognitionAlternative").msgclass
WordInfo = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.WordInfo").msgclass
NormalizedVertex = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.NormalizedVertex").msgclass
NormalizedBoundingPoly = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.NormalizedBoundingPoly").msgclass
TextSegment = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.TextSegment").msgclass
TextFrame = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.TextFrame").msgclass
TextAnnotation = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.TextAnnotation").msgclass
ObjectTrackingFrame = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.ObjectTrackingFrame").msgclass
ObjectTrackingAnnotation = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.ObjectTrackingAnnotation").msgclass
LogoRecognitionAnnotation = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.LogoRecognitionAnnotation").msgclass
Feature = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.Feature").enummodule
LabelDetectionMode = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.LabelDetectionMode").enummodule
Likelihood = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.cloud.videointelligence.v1.Likelihood").enummodule
end
end
end
end
| 66.377644 | 174 | 0.764144 |
6a28386461823d3bc57d3b49fcb1bb8948eab547 | 3,169 | require 'date'
require_relative '../../utility'
require_relative './server-item'
require_relative './flavor-item'
require_relative './image-item'
# Nocoah
module Nocoah
# Types
module Types
# Compute
module Compute
# Rebuild virtual machine result
class RebuildServerResult < ServerItem
# @return [String] Server status
attr_reader :status
# @return [DateTime] Server updated
attr_reader :updated
# @return [String] Host ID
attr_reader :host_id
# @return [Array<Nocoah::Types::Compute::ServerNetworkItem>] Addresses
attr_reader :addresses
# @return [Nocoah::Types::Compute::ImageItem] Used image
# @note :image.name is nil
attr_reader :image
# @return [Nocoah::Types::Compute::FlavorItem] Used flavor
# @note :flavor.name is nil
attr_reader :flavor
# @return [String] User ID
attr_reader :user_id
# @return [DateTime] Server created time
attr_reader :created
# @return [String] Tenant ID
attr_reader :tenant_id
# @return [String] Disk configuration
attr_reader :disk_config
# @return [String] IPv4 address that should be used to access this server
attr_reader :access_ipv4
# @return [String] IPv6 address that should be used to access this server
attr_reader :access_ipv6
# @return [Integer] A percentage value of the operation progress
attr_reader :progress
# @return [Hash] Server metadata
attr_reader :metadata
# @return [String] Root password
attr_reader :admin_password
# Creates a new {RebuildServerResult} class instance.
#
# @param [Hash] data Hash data
def initialize( data )
super( data )
@status = data['status']
@updated = DateTime.parse( data['updated'] ) rescue nil
@host_id = data['hostId']
@addresses = data['addresses'].map { | label, ips | ServerNetworkItem.new( label, ips ) } rescue []
@image = ImageItem.new( data['image'] ) rescue nil
@flavor = FlavorItem.new( data['flavor'] ) rescue nil
@user_id = data['user_id']
@created = DateTime.parse( data['created'] ) rescue nil
@tenant_id = data['tenant_id']
@disk_config = data['OS-DCF:diskConfig']
@access_ipv4 = data['accessIPv4']
@access_ipv6 = data['accessIPv6']
@progress = data['progress']
@config_drive = Utility.to_b( data['config_drive'] )
@admin_password = data['adminPass']
end
end
end
end
end | 39.123457 | 119 | 0.517198 |
391b51f3338f4571bca218953dcc873b698ea065 | 116 | FactoryBot.define do
factory :book do
title { "My Personal Hero" }
author { "I.Ron Butterfly" }
end
end
| 16.571429 | 32 | 0.646552 |
4a75724c82f74ce3ee3e15a1842a0d6f86e2b6c1 | 13,239 | feature 'User is', js: true do
let!(:admin) { FactoryBot.create(:user, :admin) }
let!(:john) { FactoryBot.create(:user, :john) }
let!(:blocked_admin) { FactoryBot.create(:user, :blocked_admin) }
scenario 'created without validation errors' do
signin(admin.email, admin.password)
click_on 'Users'
expect(page).to have_content 'Users'
expect_widget_presence
users = [
['Blocked Doe', '[email protected]', 'Administrator', 'Marketing', 'LLC Tools', ''],
['John Doe', '[email protected]', 'User', 'Marketing', 'LLC Tools', ''],
['Christopher Johnson', '[email protected]', 'Administrator', 'Administrators', 'LLC Tools', '']
]
expect(table_lines).to eq users
button.click
expect(header3.text).to eq 'Add user'
expect(label_node('user_name').text).to eq 'First name'
expect(label_node('user_middle_name').text).to eq 'Middle name'
expect(label_node('user_last_name').text).to eq 'Last name'
expect(label_node('user_email').text).to eq 'Email'
expect(label_node('user_role').text).to eq 'Role'
expect(label_node('user_company').text).to eq 'Company'
expect(label_node('user_department').text).to eq 'Department'
expect(label_node('user_password').text).to eq 'Password'
expect(label_node('user_password_confirmation').text).to eq 'Password confirmation'
button.click
expect(validation_errors_container.find('.alert').text).to eq '6 errors prevented the user from being saved:'
expect(validation_errors_container.all('li').map(&:text)).to eq [
'Email is not specified',
'Password is not specified',
'First name is not specified',
'Last name is not specified',
'Company is not specified',
'Department is not specified'
]
expect(is_input_in_error?('user_name')).to be true
expect(input_error_text('user_name')).to eq 'is not specified'
expect(is_input_in_error?('user_last_name')).to be true
expect(input_error_text('user_last_name')).to eq 'is not specified'
expect(is_input_in_error?('user_email')).to be true
expect(input_error_text('user_email')).to eq 'is not specified'
expect(is_input_in_error?('user_company')).to be true
expect(input_error_text('user_company')).to eq 'is not specified'
expect(is_input_in_error?('user_department')).to be true
expect(input_error_text('user_department')).to eq 'is not specified'
expect(is_input_in_error?('user_password')).to be true
expect(input_error_text('user_password')).to eq 'is not specified'
input_by_label('user_email').set('testtest')
button.click
expect(validation_errors_container.find('.alert').text).to eq '6 errors prevented the user from being saved:'
expect(input_error_text('user_email')).to eq 'is invalid'
input_by_label('user_password').set('q')
button.click
expect(validation_errors_container.find('.alert').text).to eq '7 errors prevented the user from being saved:'
expect(input_error_text('user_password')).to eq 'is too short'
expect(input_error_text('user_password_confirmation')).to eq 'is blank'
input_by_label('user_name').set 'Mark'
input_by_label('user_middle_name').set 'Jay'
input_by_label('user_last_name').set 'Jenkins'
input_by_label('user_email').set '[email protected]'
input_by_label('user_company').set 'LLC Tools'
input_by_label('user_department').set 'Administrators'
input_by_label('user_password').set 'qwe123123123'
input_by_label('user_password_confirmation').set 'qwe123123123'
select_by_label('user_role').find('option[value="admin"]').select_option
button.click
users = [
['Blocked Doe', '[email protected]', 'Administrator', 'Marketing', 'LLC Tools', ''],
['John Doe', '[email protected]', 'User', 'Marketing', 'LLC Tools', ''],
['Mark Jenkins', '[email protected]', 'Administrator', 'Administrators', 'LLC Tools', ''],
['Christopher Johnson', '[email protected]', 'Administrator', 'Administrators', 'LLC Tools', '']
]
expect(table_lines).to eq users
mark = User.find_by_name('Mark')
expect(mark.middle_name).to eq 'Jay'
expect(mark.last_name).to eq 'Jenkins'
expect(mark.email).to eq '[email protected]'
expect(mark.role).to eq 'admin'
expect(mark.company).to eq 'LLC Tools'
expect(mark.department).to eq 'Administrators'
end
scenario 'able to control API token' do
signin(admin.email, admin.password)
click_on 'Users'
expect(page).to have_content 'Users'
expect_widget_presence
expect(admin.api_token).to be_nil
link_by_href("/users/#{admin.id}").click
expect(header.text).to eq('User profile')
expect(user_edit(admin).text).to eq('Edit')
expect(user_generate_api_token(admin).text).to eq('Generate API token')
expect(user_data).to eq [
'Full name: Christopher Johnson',
'Email: [email protected]',
'Role: Administrator',
'Company: LLC Tools',
'Department: Administrators',
'API token:'
]
user_generate_api_token(admin).click
expect(user_generate_api_token(admin).text).to eq 'Renew API token'
expect(is_button_red?("/users/#{admin.id}/generate_api_token")).to be true
admin.reload
expect(user_clear_api_token(admin).text).to eq 'Delete API token'
expect(is_button_red?("/users/#{admin.id}/clear_api_token")).to be true
expect(admin.api_token).not_to be_nil
expect(user_data).to eq [
'Full name: Christopher Johnson',
'Email: [email protected]',
'Role: Administrator',
'Company: LLC Tools',
'Department: Administrators',
"API token: #{admin.api_token}"
]
user_clear_api_token(admin).click
expect(active_modal_dialog_body.text).to eq 'Current API token will be deleted. Are you sure?'
expect(active_modal_dialog_cancel.text).to eq 'Cancel'
expect(active_modal_dialog_proceed.text).to eq 'Yes, delete'
active_modal_dialog_cancel.click
expect(active_modal_dialogs.length).to eq 0
user_clear_api_token(admin).click
expect(active_modal_dialog_body.text).to eq 'Current API token will be deleted. Are you sure?'
expect(active_modal_dialog_cancel.text).to eq 'Cancel'
expect(active_modal_dialog_proceed.text).to eq 'Yes, delete'
active_modal_dialog_proceed.click
expect(active_modal_dialogs.length).to eq 0
expect(user_data).to eq [
'Full name: Christopher Johnson',
'Email: [email protected]',
'Role: Administrator',
'Company: LLC Tools',
'Department: Administrators',
'API token:'
]
expect(user_edit(admin).text).to eq 'Edit'
expect(user_generate_api_token(admin).text).to eq 'Generate API token'
admin.reload
expect(admin.api_token).to be_nil
user_generate_api_token(admin).click
expect(user_generate_api_token(admin).text).to eq('Renew API token')
expect(is_button_red?("/users/#{admin.id}/generate_api_token")).to be true
admin.reload
expect(user_data).to eq [
'Full name: Christopher Johnson',
'Email: [email protected]',
'Role: Administrator',
'Company: LLC Tools',
'Department: Administrators',
"API token: #{admin.api_token}"
]
user_generate_api_token(admin).click
expect(active_modal_dialog_body.text).to eq 'New API token will replace the current one. Are you sure?'
expect(active_modal_dialog_cancel.text).to eq 'Cancel'
expect(active_modal_dialog_proceed.text).to eq 'Yes, renew'
active_modal_dialog_cancel.click
expect(active_modal_dialogs.length).to eq 0
user_generate_api_token(admin).click
expect(active_modal_dialog_body.text).to eq 'New API token will replace the current one. Are you sure?'
expect(active_modal_dialog_cancel.text).to eq 'Cancel'
expect(active_modal_dialog_proceed.text).to eq 'Yes, renew'
active_modal_dialog_proceed.click
expect(active_modal_dialogs.length).to eq 0
previous_api_token = admin.api_token
admin.reload
expect(admin.api_token).not_to eq previous_api_token
expect(user_data).to eq [
'Full name: Christopher Johnson',
'Email: [email protected]',
'Role: Administrator',
'Company: LLC Tools',
'Department: Administrators',
"API token: #{admin.api_token}"
]
end
scenario 'editable' do
signin(admin.email, admin.password)
click_on 'Users'
expect(page).to have_content 'Users'
expect_widget_presence
link_by_href("/users/#{john.id}").click
expect_widget_presence
expect(header.text).to eq 'User profile'
expect(user_edit(john).text).to eq 'Edit'
expect(user_generate_api_token(john).text).to eq 'Generate API token'
expect(user_data).to eq([
'Full name: John Doe',
'Email: [email protected]',
'Role: User',
'Company: LLC Tools',
'Department: Marketing',
'API token:'
])
user_edit(john).click
expect(label_node('user_name').text).to eq 'First name'
expect(label_node('user_middle_name').text).to eq 'Middle name'
expect(label_node('user_last_name').text).to eq 'Last name'
expect(label_node('user_email').text).to eq 'Email'
expect(label_node('user_role').text).to eq 'Role'
expect(label_node('user_company').text).to eq 'Company'
expect(label_node('user_department').text).to eq 'Department'
expect(label_node('user_password').text).to eq 'Password'
expect(label_node('user_password_confirmation').text).to eq 'Password confirmation'
input_by_label('user_name').set 'Mark'
input_by_label('user_middle_name').set 'Jay'
input_by_label('user_last_name').set 'Jenkins'
input_by_label('user_email').set '[email protected]'
input_by_label('user_company').set 'LLC Tools'
input_by_label('user_department').set 'Administrators'
input_by_label('user_password').set 'qwe123123123'
input_by_label('user_password_confirmation').set 'qwe123123123'
select_by_label('user_role').find('option[value="admin"]').select_option
button.click
users = [
['Blocked Doe', '[email protected]', 'Administrator', 'Marketing', 'LLC Tools', ''],
['Mark Jenkins', '[email protected]', 'Administrator', 'Administrators', 'LLC Tools', ''],
['Christopher Johnson', '[email protected]', 'Administrator', 'Administrators', 'LLC Tools', '']
]
expect(table_lines).to eq users
previous_password = john.encrypted_password
john.reload
expect(john.name).to eq 'Mark'
expect(john.middle_name).to eq 'Jay'
expect(john.last_name).to eq 'Jenkins'
expect(john.email).to eq '[email protected]'
expect(john.role).to eq 'admin'
expect(john.company).to eq 'LLC Tools'
expect(john.department).to eq 'Administrators'
expect(john.encrypted_password).not_to eq previous_password
end
scenario 'inaccessible for ordinary user' do
signin(john.email, john.password)
expect(page).not_to have_content 'Users'
end
scenario 'inaccessible for blocked user' do
signin(blocked_admin.email, blocked_admin.password)
expect(page).not_to have_content 'Orders list'
end
end
| 46.12892 | 113 | 0.590377 |
f76e7d99eee7666292d8b9b2c9aa1eabac3ffffd | 3,357 | require 'spec_helper'
describe Cointrader::Client, vcr: true do
def limit_buy
subject.limit_buy(total_quantity: 1, price: 10)
end
def limit_sell
subject.limit_sell(total_quantity: 1, price: 10)
end
def market_buy
subject.market_buy(total_amount: 1)
end
def market_sell
subject.market_sell(total_amount: 1)
end
describe 'stats' do
describe '#symbol' do
it 'returns supported currencies' do
response = subject.symbol
expect_success(response)
expect(response['data'][0]['name']).to eq 'Bitcoin (BTC)'
end
end
describe '#stats_24h' do
it 'returns 24 hour sliding statistics' do
response = subject.stats_24h
expect_success(response)
end
end
describe '#stats_7d' do
it 'returns 7 day sliding statistics' do
response = subject.stats_7d
expect_success(response)
end
end
describe '#orders' do
it 'returns open orders' do
response = subject.orders
expect_success(response)
end
end
end
describe 'account' do
describe '#balance' do
it 'returns a balance' do
response = subject.balance
expect_success(response)
expect(response['data']['BTC']['available']).not_to be_nil
end
end
describe '#tradehistory' do
it 'returns trade history' do
response = subject.tradehistory
expect_success(response)
end
end
end
describe 'order' do
describe '#limit_buy' do
it 'returns an order' do
response = limit_buy
expect_success(response)
expect(response['data']['id']).not_to be_nil
end
it 'throws an error when there are insufficient funds' do
expect { subject.limit_buy(price: 1_000_000, total_quantity: 1) }.to raise_error(Cointrader::LimitBuyError)
end
end
describe '#limit_sell' do
it 'returns an order' do
response = limit_sell
expect_success(response)
expect(response['data']['id']).not_to be_nil
end
end
describe '#cancel' do
let(:order) { limit_buy }
it 'cancels an order' do
response = subject.cancel(order_id: order['data']['id'])
expect_success(response)
end
end
describe '#list' do
context 'when there are orders' do
let(:order) { limit_buy }
after { subject.cancel(order_id: order['data']['id'] )}
it 'lists open limit orders' do
order
response = subject.list
expect_success(response)
end
end
context 'when there are no orders' do
it 'throws an error' do
expect { subject.list }.to raise_error(Cointrader::NoOpenOrders)
end
end
end
describe '#market_buy' do
it 'returns an order' do
response = market_buy
expect_success(response)
expect(response['message']).not_to eq('Unauthorized')
end
end
describe '#market_sell' do
it 'returns an order' do
response = market_sell
expect_success(response)
expect(response['message']).not_to eq('Unauthorized')
end
end
describe '#trades' do
it 'lists recent trades executed' do
response = subject.trades
expect_success(response)
end
end
end
end
| 23.640845 | 115 | 0.617516 |
87d300a3e9c45842bae5615befe1390028e6430a | 733 | module TD::Types
# Describes a user profile photo.
#
# @attr id [Integer] Photo identifier; 0 for an empty photo.
# Can be used to find a photo in a list of user profile photos.
# @attr small [TD::Types::File] A small (160x160) user profile photo.
# The file can be downloaded only before the photo is changed.
# @attr big [TD::Types::File] A big (640x640) user profile photo.
# The file can be downloaded only before the photo is changed.
# @attr has_animation [Boolean] True, if the photo has animated variant.
class ProfilePhoto < Base
attribute :id, TD::Types::Integer
attribute :small, TD::Types::File
attribute :big, TD::Types::File
attribute :has_animation, TD::Types::Bool
end
end
| 40.722222 | 74 | 0.697135 |
e9fb6e21ea3ed27f455d55ab7556cd18343ff756 | 1,271 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'rails_log_deinterleaver/version'
Gem::Specification.new do |spec|
spec.name = "rails_log_deinterleaver"
spec.version = RailsLogDeinterleaver::VERSION
spec.authors = ["Matt Fawcett"]
spec.email = ["[email protected]"]
spec.summary = "Convert interleaved rails logs into a more readable format"
spec.description = %q(Multiple rails instances writing to the same log cause entries to be interleaved,
making them hard to ready. This command line script groups them by request, using the pid. )
spec.homepage = "https://github.com/mattfawcett/rails_log_deinterleaver"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "bin"
spec.executables = "rails_log_deinterleaver"
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.10"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "minitest", "~> 5.7"
spec.add_dependency "file-tail", "~> 1.1"
spec.add_dependency "trollop", "~> 2.1"
end
| 42.366667 | 118 | 0.674272 |
62b4801f712504d57e37bb3f964de25e86bbd6ef | 426 | require 'rubygems/test_case'
require 'rubygems/name_tuple'
class TestGemNameTuple < Gem::TestCase
def test_platform_normalization
n = Gem::NameTuple.new "a", Gem::Version.new(0), "ruby"
assert_equal "ruby", n.platform
n = Gem::NameTuple.new "a", Gem::Version.new(0), nil
assert_equal "ruby", n.platform
n = Gem::NameTuple.new "a", Gem::Version.new(0), ""
assert_equal "ruby", n.platform
end
end
| 26.625 | 59 | 0.685446 |
18c4ce575da362d68adf97539c12cb3f832be1c3 | 978 | # coding: utf-8
Gem::Specification.new do |spec|
spec.name = "capybara-timeout_reporter"
spec.version = "0.2.2"
spec.authors = ["Vitalii Grygoruk"]
spec.email = ["vitaliy[dot]grigoruk[at]gmail[dot]com"]
spec.summary = %q{Detecting and reporting capybara sync timeouts}
spec.description = %q{Allows you to execute a block or raise a warning if you use a finder that reaches capybara's timeout.}
spec.homepage = "https://github.com/vgrigoruk/capybara-timeout_reporter"
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.required_ruby_version = ">= 1.9.3"
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_dependency "capybara", "~> 2.0"
end
| 40.75 | 128 | 0.656442 |
01fcac943fa520985555e4e01264a3ab2d7f1b83 | 5,068 | module Fog
module Parsers
module AWS
module RDS
class DbParser < Fog::Parsers::Base
def reset
@db_instance = fresh_instance
end
def fresh_instance
{'PendingModifiedValues' => [], 'DBSecurityGroups' => [], 'ReadReplicaDBInstanceIdentifiers' => [], 'Endpoint' => {}}
end
def start_element(name, attrs = [])
super
case name
when 'PendingModifiedValues'
@in_pending_modified_values = true
@pending_modified_values = {}
when 'DBSecurityGroups'
@in_db_security_groups = true
@db_security_groups = []
when 'DBSecurityGroup'
@db_security_group = {}
when 'Endpoint'
@in_endpoint = true
@endpoint = {}
when 'DBParameterGroup'
@db_parameter_group = {}
when 'DBParameterGroups'
@in_db_parameter_groups = true
@db_parameter_groups = []
when 'VpcSecurityGroupMembership'
@vpc_security_group = {}
when 'VpcSecurityGroups'
@in_vpc_security_groups = true
@vpc_security_groups = []
end
end
def end_element(name)
case name
when 'LatestRestorableTime', 'InstanceCreateTime'
@db_instance[name] = Time.parse value
when 'Engine', 'DBInstanceStatus', 'DBInstanceIdentifier',
'PreferredBackupWindow', 'PreferredMaintenanceWindow',
'AvailabilityZone', 'MasterUsername', 'DBName', 'LicenseModel',
'DBSubnetGroupName'
@db_instance[name] = value
when 'MultiAZ', 'AutoMinorVersionUpgrade', 'PubliclyAccessible'
if value == 'false'
@db_instance[name] = false
else
@db_instance[name] = true
end
when 'DBParameterGroups'
@in_db_parameter_groups = false
@db_instance['DBParameterGroups'] = @db_parameter_groups
when 'DBParameterGroup'
@db_parameter_groups << @db_parameter_group
@db_parameter_group = {}
when 'ParameterApplyStatus', 'DBParameterGroupName'
if @in_db_parameter_groups
@db_parameter_group[name] = value
end
when 'BackupRetentionPeriod'
if @in_pending_modified_values
@pending_modified_values[name] = value.to_i
else
@db_instance[name] = value.to_i
end
when 'DBInstanceClass', 'EngineVersion', 'MasterUserPassword',
'MultiAZ', 'Iops', 'AllocatedStorage'
if @in_pending_modified_values
@pending_modified_values[name] = value
else
@db_instance[name] = value
end
when 'DBSecurityGroups'
@in_db_security_groups = false
@db_instance['DBSecurityGroups'] = @db_security_groups
when 'DBSecurityGroupName'
@db_security_group[name]=value
when 'DBSecurityGroup'
@db_security_groups << @db_security_group
@db_security_group = {}
when 'VpcSecurityGroups'
@in_vpc_security_groups = false
@db_instance['VpcSecurityGroups'] = @vpc_security_groups
when 'VpcSecurityGroupMembership'
@vpc_security_groups << @vpc_security_group
@vpc_security_group = {}
when 'VpcSecurityGroupId'
@vpc_security_group[name] = value
when 'Status'
# Unfortunately, status is used in VpcSecurityGroupMemebership and
# DBSecurityGroups
if @in_db_security_groups
@db_security_group[name]=value
end
if @in_vpc_security_groups
@vpc_security_group[name] = value
end
when 'Address'
@endpoint[name] = value
when 'Port'
if @in_pending_modified_values
@pending_modified_values[name] = value.to_i
elsif @in_endpoint
@endpoint[name] = value.to_i
end
when 'PendingModifiedValues'
@in_pending_modified_values = false
@db_instance['PendingModifiedValues'] = @pending_modified_values
when 'Endpoint'
@in_endpoint = false
@db_instance['Endpoint'] = @endpoint
when 'ReadReplicaDBInstanceIdentifier'
@db_instance['ReadReplicaDBInstanceIdentifiers'] << value
when 'ReadReplicaSourceDBInstanceIdentifier'
@db_instance['ReadReplicaSourceDBInstanceIdentifier'] = value
when 'DBInstance'
@db_instance = fresh_instance
end
end
end
end
end
end
end
| 36.992701 | 129 | 0.549132 |
21b6bdf957665fb0756201b813c027f035e9c7b2 | 462 | # frozen_string_literal: true
module Scaffoldable
module BatchableHelper
def batchable_element_viewable?(element_model_instance, options = {})
result = (element_model_instance.selected.nil? || element_model_instance.selected)
result = options[:confirming] ? result && options[:confirming] : true unless options[:confirming].nil?
result
end
end
end
ActiveSupport.on_load(:action_view) do
include Scaffoldable::BatchableHelper
end
| 30.8 | 108 | 0.761905 |
081663095bd13016e3e373f6b4d6f28ee1085026 | 2,067 |
require 'sightstone/modules/sightstone_base_module'
require 'sightstone/summoner'
require 'sightstone/player_stats_summary'
require 'sightstone/ranked_stats'
module Sightstone
# Module to receive stats
class StatsModule < SightstoneBaseModule
def initialize(sightstone)
@sightstone = sightstone
end
# get a summary of stats for a summoner
# @param [Summoner, Fixnum] summoner summoner object of name
# @param optional [Hash] optional arguments: :region => replaces default region
# @ return [PlayerStatsSummaryList] of the summoner
def summary(summoner, optional={})
region = optional[:region] || @sightstone.region
season = optional[:season]
id = if summoner.is_a? Summoner
summoner.id
else
summoner
end
uri = "https://prod.api.pvp.net/api/lol/#{region}/v1.2/stats/by-summoner/#{id}/summary"
response = if season.nil?
_get_api_response(uri)
else
_get_api_response(uri, {'season' => season})
end
_parse_response(response) { |resp|
data = JSON.parse(resp)
statList = PlayerStatsSummaryList.new(data)
if block_given?
yield statList
else
return statList
end
}
end
# get a summary of stats for a summoner
# @param [Summoner, Fixnum] summoner summoner object of name
# @param optional [Hash] optional arguments: :region => replaces default region
# @ return [RankedStats] of the summoner
def ranked(summoner, optional={})
region = optional[:region] || @sightstone.region
season = optional[:season]
id = if summoner.is_a? Summoner
summoner.id
else
summoner
end
uri = "https://prod.api.pvp.net/api/lol/#{region}/v1.2/stats/by-summoner/#{id}/ranked"
response = if season.nil?
_get_api_response(uri)
else
_get_api_response(uri, {'season' => season})
end
_parse_response(response) { |resp|
data = JSON.parse(resp)
stats = RankedStats.new(data)
if block_given?
yield stats
else
return stats
end
}
end
end
end | 27.197368 | 91 | 0.670537 |
87573b91e80f8119ded79b9b2cb0156a4666e2f3 | 815 | # encoding: utf-8
require 'spec_helper'
require 'nokogiri'
feature 'Analytics' do
before(:all) do
@stat_new_courses = File.new('spec/fixtures/splunk_new_courses.xml').read
@stat_new_records = File.new('spec/fixtures/splunk_new_records.xml').read
@stat_view = File.new('spec/fixtures/splunk_view.xml').read
end
before(:each) do
sign_in_developer
end
after(:each) do
sign_out_developer
end
scenario 'is on statistic page' do
visit analytics_path
expect(page).to have_selector('h3', :text => 'Video Analytics Overview')
expect(@stat_new_courses).to have_content("12")
expect(@stat_new_records).to have_content("6")
doc = Nokogiri::XML::Document.parse(@stat_view)
expect(doc).to have_content("3")
end
end | 32.6 | 78 | 0.671166 |
0166f436dd6a291322668d4df767f63ca2468842 | 232 | class RenameRegions < ActiveRecord::Migration
def change
Region.all.each do |region|
region.name = region.name.sub ' район', ''
region.name = region.name.sub 'поселение ', ''
region.save!
end
end
end
| 19.333333 | 52 | 0.637931 |
6aa4d21d35f10dbf78d25d61fbe45a5f7e952a6d | 1,386 | class Members::RegistrationsController < Devise::RegistrationsController
# before_filter :configure_sign_up_params, only: [:create]
# before_filter :configure_account_update_params, only: [:update]
# GET /resource/sign_up
# def new
# super
# end
# POST /resource
# def create
# super
# end
# GET /resource/edit
# def edit
# super
# end
# PUT /resource
# def update
# super
# end
# DELETE /resource
# def destroy
# super
# end
# GET /resource/cancel
# Forces the session data which is usually expired after sign
# in to be expired now. This is useful if the user wants to
# cancel oauth signing in/up in the middle of the process,
# removing all OAuth session data.
# def cancel
# super
# end
# protected
# If you have extra params to permit, append them to the sanitizer.
# def configure_sign_up_params
# devise_parameter_sanitizer.for(:sign_up) << :attribute
# end
# If you have extra params to permit, append them to the sanitizer.
# def configure_account_update_params
# devise_parameter_sanitizer.for(:account_update) << :attribute
# end
# The path used after sign up.
# def after_sign_up_path_for(resource)
# super(resource)
# end
# The path used after sign up for inactive accounts.
# def after_inactive_sign_up_path_for(resource)
# super(resource)
# end
end
| 22.721311 | 72 | 0.69697 |
01b666c648ea9a600e180a05af4a0d405d10af07 | 1,299 | require 'rdf'
# TODO: disable until solve memory exhaust
# require 'rdf/raptor'
require 'rdf/turtle'
require 'zlib'
module DbSNP::RDF
module Writer
class Turtle
class << self
def open(path, compress: true)
f = if compress
Zlib::GzipWriter.open(path)
else
File.open(path, 'w')
end
writer = new(f)
return writer unless block_given?
begin
yield writer
ensure
if f && !f.closed?
f.close
end
end
end
end
def initialize(io = STDOUT)
@io = io
yield self if block_given?
end
# @param [RDF::Enumerable, RDF::Statement, #to_rdf] data
# @return [Integer] the number of bytes written
def <<(data)
buffer = ::RDF::Writer.for(:turtle).buffer({ prefixes: PREFIXES }) do |writer|
writer << data
end
buffer.gsub!(/^@.*\n/, '')
unless @header_written
header_options = { prefixes: PREFIXES.merge(rdf: ::RDF::RDFV.to_s), stream: true }
::RDF::Turtle::Writer.new(@io, header_options).write_epilogue
@header_written = true
end
@io.write buffer
end
end
end
end
| 22.396552 | 92 | 0.525019 |
b97801f3453fe18de301a6b122016d989bc0a7bb | 1,276 | require_relative '../../../search_test'
require_relative '../../../generator/group_metadata'
module USCoreTestKit
module USCoreV311
class EncounterIdentifierSearchTest < Inferno::Test
include USCoreTestKit::SearchTest
title 'Server returns valid results for Encounter search by identifier'
description %(
A server SHOULD support searching by
identifier on the Encounter resource. This test
will pass if resources are returned and match the search criteria. If
none are returned, the test is skipped.
[US Core Server CapabilityStatement](http://hl7.org/fhir/us/core/STU3.1.1/CapabilityStatement-us-core-server.html)
)
id :us_core_v311_encounter_identifier_search_test
optional
def self.properties
@properties ||= SearchTestProperties.new(
resource_type: 'Encounter',
search_param_names: ['identifier'],
possible_status_search: true,
token_search_params: ['identifier']
)
end
def self.metadata
@metadata ||= Generator::GroupMetadata.new(YAML.load_file(File.join(__dir__, 'metadata.yml')))
end
def scratch_resources
scratch[:encounter_resources] ||= {}
end
run do
run_search_test
end
end
end
end
| 27.73913 | 114 | 0.691223 |
260dfedee0454b0b3e6ef9c1045cdcdf76edf852 | 552 | module VolleyMotion
class PostRequest < Com::Android::Volley::Request
def parseNetworkResponse(response)
# p response
result = response.data
# p response.toString
# s = Java::Lang::String.new(response.data)
# p s
# p response.result.toString
return Com::Android::Volley::Response.success(response, Com::Android::Volley::Toolbox::HttpHeaderParser.parseCacheHeaders(response))
end
def deliverResponse(response)
listener = getListener
listener.onResponse(response)
end
end
end
| 25.090909 | 138 | 0.686594 |
d5004941707e5f2fe7b1ce39a105d9bd04587117 | 2,184 | Окончательный три согласны бакалавра Сэм Вуд является идеальным парнем - но кто он будет выбирать?
Тайна?
Лана Джевонс-ребята, Сара Маккей и Снежана Маркоски может невольно показал, кто выигрывает холостяк.
Женщина, которая с Сэм Вуд заканчивается холостяка были обмотаны в полной секретности.
И три девушки, осталось конечно, не позволяя скольжения ли тот, кто получил его окончательный роза.
Но когда мы проверили с Сара Маккей, Снежана Маркоски и Лана Джевонс-ребята накануне три два, они могут непреднамеренно отдали ни малейшего понятия о том, кто будет победителем.
Сэм Вуд держит его губы, плотно запечатаны до четверга финал
Все три женщины воском лирическими над почему древесина является совершенным человеком, сославшись на его чувство юмора, честолюбие, семейные ценности и позитивность как причины, они бы каждая любовь быть его партнером.
Однако когда задал вопрос, "Если не вы, кто должен получить древесины окончательный роза?," их ответы могли бы обеспечить спойлер о том, кто выиграл сердце холостяков.
Джевонс стипендиатов и Маркоски были быстро имя Mackay, отдельно от себя, лучший матч для древесины.
Сара Маккей и Сэм Вуд совместно легко раппорт с первого дня.
«С момента я вошел в дом, чтение (Сара) и Сэм энергии, которую я чувствовал, как они были вполне совместимы, и я продолжал думать, что в ходе шоу, "сказал Джевонс-стипендиатов.
«Сара действительно вниз на землю, она это так весело, чтобы быть вокруг,»-добавил Маркоски.
Я видел их вместе, и они имеют то химия там.
Они чувствуют себя хорошо и комфортно друг с другом.
Сара Маккей считает, что она и Сэм Вуд будет хорошо подходит как пара.
Со своей стороны Маккей сказал на прошлой неделе визит домой даты заставило ее реализации древесины может быть «один».
«Однажды я видел его с моими друзьями и семьи, я понял это, очевидно, не просто игра - я искренне инвестировал в него сейчас,»,-сказала она.
И спросил, кто должен выбрать древесину если не ее, она была загадочной.
«Я не знаю, если я могу сказать»,-сказала она.
Я люблю оставшиеся девушки одинаково - это связь между Снежана и Лана.
Холостяк проветривает среду, 7: 30 вечера на 10.
Первоначально опубликовано как Сара лучший выбор для Сэм Вуд?
| 91 | 219 | 0.804487 |
e80adcc82dbc96c652a3e0ca30cd080f014f0c0f | 759 | class UserNameChangeRequest < ApplicationRecord
belongs_to :user
belongs_to :approver, class_name: "User", optional: true
validate :not_limited, on: :create
validates :desired_name, user_name: true, confirmation: true, on: :create
validates_presence_of :original_name, :desired_name
after_create :update_name!
def self.visible(user)
if user.is_moderator?
all
elsif user.is_member?
where(user: User.undeleted)
else
none
end
end
def update_name!
user.update!(name: desired_name)
end
def not_limited
if UserNameChangeRequest.unscoped.where(user: user).where("created_at >= ?", 1.week.ago).exists?
errors[:base] << "You can only submit one name change request per week"
end
end
end
| 24.483871 | 100 | 0.711462 |
0177bc8173c430a684d58bbf63d16620dfb228a3 | 603 | require 'spec_helper'
module Spree
describe 'Countries', type: :feature do
stub_authorization!
it 'deletes a state', js: true do
visit spree.admin_countries_path
click_link 'New Country'
fill_in 'Name', with: 'Brazil'
fill_in 'Iso Name', with: 'BRL'
fill_in 'Iso', with: 'BR'
fill_in 'Iso3', with: 'BRL'
click_button 'Create'
accept_confirm do
click_icon :delete
end
expect(page).to have_content('has been successfully removed!')
expect { Country.find(country.id) }.to raise_error(StandardError)
end
end
end
| 23.192308 | 71 | 0.646766 |
bbf5a78fb0ba3f6d7b89886525de6274f5738cb9 | 47,208 | # -*- coding: binary -*-
require 'rex/ui/text/output/buffer/stdout'
module Msf
module Ui
module Console
module CommandDispatcher
#
# {CommandDispatcher} for commands related to background jobs in Metasploit Framework.
#
class Modules
include Msf::Ui::Console::CommandDispatcher
include Msf::Ui::Console::CommandDispatcher::Common
@@search_opts = Rex::Parser::Arguments.new(
'-h' => [false, 'Help banner'],
'-o' => [true, 'Send output to a file in csv format'],
'-S' => [true, 'Search string for row filter'],
'-u' => [false, 'Use module if there is one result']
)
def commands
{
"back" => "Move back from the current context",
"advanced" => "Displays advanced options for one or more modules",
"info" => "Displays information about one or more modules",
"options" => "Displays global options or for one or more modules",
"loadpath" => "Searches for and loads modules from a path",
"popm" => "Pops the latest module off the stack and makes it active",
"pushm" => "Pushes the active or list of modules onto the module stack",
"listm" => "List the module stack",
"clearm" => "Clear the module stack",
"previous" => "Sets the previously loaded module as the current module",
"reload_all" => "Reloads all modules from all defined module paths",
"search" => "Searches module names and descriptions",
"show" => "Displays modules of a given type, or all modules",
"use" => "Interact with a module by name or search term/index",
}
end
#
# Initializes the datastore cache
#
def initialize(driver)
super
@dscache = {}
@previous_module = nil
@module_name_stack = []
@module_search_results = []
@@payload_show_results = []
@dangerzone_map = nil
end
#
# Returns the name of the command dispatcher.
#
def name
"Module"
end
def cmd_advanced_help
print_line 'Usage: advanced [mod1 mod2 ...]'
print_line
print_line 'Queries the supplied module or modules for advanced options. If no module is given,'
print_line 'show advanced options for the currently active module.'
print_line
end
def cmd_advanced(*args)
if args.empty?
if (active_module)
show_advanced_options(active_module)
return true
else
print_error('No module active')
return false
end
end
args.each { |name|
mod = framework.modules.create(name)
if (mod == nil)
print_error("Invalid module: #{name}")
else
show_advanced_options(mod)
end
}
end
def cmd_info_help
print_line "Usage: info <module name> [mod2 mod3 ...]"
print_line
print_line "Options:"
print_line "* The flag '-j' will print the data in json format"
print_line "* The flag '-d' will show the markdown version with a browser. More info, but could be slow."
print_line "Queries the supplied module or modules for information. If no module is given,"
print_line "show info for the currently active module."
print_line
end
#
# Displays information about one or more module.
#
def cmd_info(*args)
dump_json = false
show_doc = false
if args.include?('-j')
args.delete('-j')
dump_json = true
end
if args.include?('-d')
args.delete('-d')
show_doc = true
end
if (args.length == 0)
if (active_module)
if dump_json
print(Serializer::Json.dump_module(active_module) + "\n")
elsif show_doc
f = Tempfile.new(["#{active_module.shortname}_doc", '.html'])
begin
print_status("Generating documentation for #{active_module.shortname}, then opening #{f.path} in a browser...")
Msf::Util::DocumentGenerator.spawn_module_document(active_module, f)
ensure
f.close if f
end
else
print(Serializer::ReadableText.dump_module(active_module))
end
return true
else
cmd_info_help
return false
end
elsif args.include? "-h"
cmd_info_help
return false
end
args.each { |name|
mod = framework.modules.create(name)
if (mod == nil)
print_error("Invalid module: #{name}")
elsif dump_json
print(Serializer::Json.dump_module(mod) + "\n")
elsif show_doc
f = Tempfile.new(["#{mod.shortname}_doc", '.html'])
begin
print_status("Generating documentation for #{mod.shortname}, then opening #{f.path} in a browser...")
Msf::Util::DocumentGenerator.spawn_module_document(mod, f)
ensure
f.close if f
end
else
print(Serializer::ReadableText.dump_module(mod))
end
}
end
def cmd_options_help
print_line 'Usage: options [mod1 mod2 ...]'
print_line
print_line 'Queries the supplied module or modules for options. If no module is given,'
print_line 'show options for the currently active module.'
print_line
end
def cmd_options(*args)
if args.empty?
if (active_module)
show_options(active_module)
return true
else
show_global_options
return true
end
end
args.each do |name|
mod = framework.modules.create(name)
if (mod == nil)
print_error("Invalid module: #{name}")
else
show_options(mod)
end
end
end
#
# Tab completion for the advanced command (same as use)
#
# @param str (see #cmd_use_tabs)
# @param words (see #cmd_use_tabs)
def cmd_advanced_tabs(str, words)
cmd_use_tabs(str, words)
end
#
# Tab completion for the advanced command (same as use)
#
# @param str (see #cmd_use_tabs)
# @param words (see #cmd_use_tabs)
def cmd_info_tabs(str, words)
cmd_use_tabs(str, words)
end
#
# Tab completion for the advanced command (same as use)
#
# @param str (see #cmd_use_tabs)
# @param words (see #cmd_use_tabs)
def cmd_options_tabs(str, words)
cmd_use_tabs(str, words)
end
def cmd_loadpath_help
print_line "Usage: loadpath </path/to/modules>"
print_line
print_line "Loads modules from the given directory which should contain subdirectories for"
print_line "module types, e.g. /path/to/modules/exploits"
print_line
end
#
# Adds one or more search paths.
#
def cmd_loadpath(*args)
if (args.length == 0 or args.include? "-h")
cmd_loadpath_help
return true
end
totals = {}
overall = 0
curr_path = nil
begin
# Walk the list of supplied search paths attempting to add each one
# along the way
args.each { |path|
curr_path = path
# Load modules, but do not consult the cache
if (counts = framework.modules.add_module_path(path))
counts.each_pair { |type, count|
totals[type] = (totals[type]) ? (totals[type] + count) : count
overall += count
}
end
}
rescue NameError, RuntimeError
log_error("Failed to add search path #{curr_path}: #{$!}")
return true
end
added = "Loaded #{overall} modules:\n"
totals.each_pair { |type, count|
added << " #{count} #{type} modules\n"
}
print(added)
end
#
# Tab completion for the loadpath command
#
# @param str [String] the string currently being typed before tab was hit
# @param words [Array<String>] the previously completed words on the command line. words is always
# at least 1 when tab completion has reached this stage since the command itself has been completed
def cmd_loadpath_tabs(str, words)
return [] if words.length > 1
# This custom completion might better than Readline's... We'll leave it for now.
#tab_complete_filenames(str,words)
paths = []
if (File.directory?(str))
paths = Dir.entries(str)
paths = paths.map { |f|
if File.directory? File.join(str,f)
File.join(str,f)
end
}
paths.delete_if { |f| f.nil? or File.basename(f) == '.' or File.basename(f) == '..' }
else
d = Dir.glob(str + "*").map { |f| f if File.directory?(f) }
d.delete_if { |f| f.nil? or f == '.' or f == '..' }
# If there's only one possibility, descend to the next level
if (1 == d.length)
paths = Dir.entries(d[0])
paths = paths.map { |f|
if File.directory? File.join(d[0],f)
File.join(d[0],f)
end
}
paths.delete_if { |f| f.nil? or File.basename(f) == '.' or File.basename(f) == '..' }
else
paths = d
end
end
paths.sort!
return paths
end
def cmd_search_help
print_line "Usage: search [<options>] [<keywords>]"
print_line
print_line "If no options or keywords are provided, cached results are displayed."
print_line
print_line "OPTIONS:"
print_line " -h Show this help information"
print_line " -o <file> Send output to a file in csv format"
print_line " -S <string> Search string for row filter"
print_line " -u Use module if there is one result"
print_line
print_line "Keywords:"
{
'aka' => 'Modules with a matching AKA (also-known-as) name',
'author' => 'Modules written by this author',
'arch' => 'Modules affecting this architecture',
'bid' => 'Modules with a matching Bugtraq ID',
'cve' => 'Modules with a matching CVE ID',
'edb' => 'Modules with a matching Exploit-DB ID',
'check' => 'Modules that support the \'check\' method',
'date' => 'Modules with a matching disclosure date',
'description' => 'Modules with a matching description',
'fullname' => 'Modules with a matching full name',
'mod_time' => 'Modules with a matching modification date',
'name' => 'Modules with a matching descriptive name',
'path' => 'Modules with a matching path',
'platform' => 'Modules affecting this platform',
'port' => 'Modules with a matching port',
'rank' => 'Modules with a matching rank (Can be descriptive (ex: \'good\') or numeric with comparison operators (ex: \'gte400\'))',
'ref' => 'Modules with a matching ref',
'reference' => 'Modules with a matching reference',
'target' => 'Modules affecting this target',
'type' => 'Modules of a specific type (exploit, payload, auxiliary, encoder, evasion, post, or nop)',
}.each_pair do |keyword, description|
print_line " #{keyword.ljust 12}: #{description}"
end
print_line
print_line "Examples:"
print_line " search cve:2009 type:exploit"
print_line
end
#
# Searches modules for specific keywords
#
def cmd_search(*args)
match = ''
search_term = nil
output_file = nil
cached = false
use = false
count = -1
@@search_opts.parse(args) do |opt, idx, val|
case opt
when '-S'
search_term = val
when '-h'
cmd_search_help
return false
when '-o'
output_file = val
when '-u'
use = true
else
match += val + ' '
end
end
if args.empty?
if @module_search_results.empty?
cmd_search_help
return false
end
cached = true
end
# Display the table of matches
tbl = generate_module_table('Matching Modules', search_term)
begin
if cached
print_status('Displaying cached results')
else
search_params = parse_search_string(match)
@module_search_results = Msf::Modules::Metadata::Cache.instance.find(search_params)
end
if @module_search_results.empty?
print_error('No results from search')
return false
end
@module_search_results.each do |m|
tbl << [
count += 1,
m.fullname,
m.disclosure_date.nil? ? '' : m.disclosure_date.strftime("%Y-%m-%d"),
RankingName[m.rank].to_s,
m.check ? 'Yes' : 'No',
m.name
]
end
if @module_search_results.length == 1 && use
used_module = @module_search_results.first.fullname
cmd_use(used_module, true)
end
rescue ArgumentError
print_error("Invalid argument(s)\n")
cmd_search_help
return false
end
if output_file
print_status("Wrote search results to #{output_file}")
::File.open(output_file, "wb") { |ofd|
ofd.write(tbl.to_csv)
}
else
print_line(tbl.to_s)
print_status("Using #{used_module}") if used_module
end
true
end
#
# Parses command line search string into a hash
#
# Resulting Hash Example:
# {"platform"=>[["android"], []]} will match modules targeting the android platform
# {"platform"=>[[], ["android"]]} will exclude modules targeting the android platform
#
def parse_search_string(search_string)
# Split search terms by space, but allow quoted strings
terms = search_string.split(/\"/).collect{|term| term.strip==term ? term : term.split(' ')}.flatten
terms.delete('')
# All terms are either included or excluded
res = {}
terms.each do |term|
keyword, search_term = term.split(":", 2)
unless search_term
search_term = keyword
keyword = 'text'
end
next if search_term.length == 0
keyword.downcase!
search_term.downcase!
res[keyword] ||=[ [], [] ]
if search_term[0,1] == "-"
next if search_term.length == 1
res[keyword][1] << search_term[1,search_term.length-1]
else
res[keyword][0] << search_term
end
end
res
end
#
# Tab completion for the search command
#
# @param str [String] the string currently being typed before tab was hit
# @param words [Array<String>] the previously completed words on the command line. words is always
# at least 1 when tab completion has reached this stage since the command itself has been completed
def cmd_search_tabs(str, words)
if words.length == 1
return @@search_opts.fmt.keys
end
[]
end
def cmd_show_help
global_opts = %w{all encoders nops exploits payloads auxiliary post plugins info options}
print_status("Valid parameters for the \"show\" command are: #{global_opts.join(", ")}")
module_opts = %w{ missing advanced evasion targets actions }
print_status("Additional module-specific parameters are: #{module_opts.join(", ")}")
end
#
# Displays the list of modules based on their type, or all modules if
# no type is provided.
#
def cmd_show(*args)
if args.empty?
print_error("Argument required\n")
cmd_show_help
return
end
mod = self.active_module
args.each { |type|
case type
when '-h'
cmd_show_help
when 'all'
show_encoders
show_nops
show_exploits
show_payloads
show_auxiliary
show_post
show_plugins
when 'encoders'
show_encoders
when 'nops'
show_nops
when 'exploits'
show_exploits
when 'payloads'
show_payloads
when 'auxiliary'
show_auxiliary
when 'post'
show_post
when 'info'
cmd_info(*args[1, args.length])
when 'options'
if (mod)
show_options(mod)
else
show_global_options
end
when 'missing'
if (mod)
show_missing(mod)
else
print_error("No module selected.")
end
when 'advanced'
if (mod)
show_advanced_options(mod)
else
print_error("No module selected.")
end
when 'evasion'
if (mod)
show_evasion_options(mod)
else
show_evasion
end
when 'sessions'
if (active_module and active_module.respond_to?(:compatible_sessions))
sessions = active_module.compatible_sessions
else
sessions = framework.sessions.keys.sort
end
print_line
print(Serializer::ReadableText.dump_sessions(framework, :session_ids => sessions))
print_line
when "plugins"
show_plugins
when "targets"
if (mod and (mod.exploit? or mod.evasion?))
show_targets(mod)
else
print_error("No exploit module selected.")
end
when "actions"
if mod && mod.kind_of?(Msf::Module::HasActions)
show_actions(mod)
else
print_error("No module with actions selected.")
end
else
print_error("Invalid parameter \"#{type}\", use \"show -h\" for more information")
end
}
end
#
# Tab completion for the show command
#
# @param str [String] the string currently being typed before tab was hit
# @param words [Array<String>] the previously completed words on the command line. words is always
# at least 1 when tab completion has reached this stage since the command itself has been completed
def cmd_show_tabs(str, words)
return [] if words.length > 1
res = %w{all encoders nops exploits payloads auxiliary post plugins options}
if (active_module)
res.concat %w{missing advanced evasion targets actions info}
if (active_module.respond_to? :compatible_sessions)
res << "sessions"
end
end
return res
end
def cmd_use_help
print_line 'Usage: use <name|term|index>'
print_line
print_line 'Interact with a module by name or search term/index.'
print_line 'If a module name is not found, it will be treated as a search term.'
print_line 'An index from the previous search results can be selected if desired.'
print_line
print_line 'Examples:'
print_line ' use exploit/windows/smb/ms17_010_eternalblue'
print_line
print_line ' use eternalblue'
print_line ' use <name|index>'
print_line
print_line ' search eternalblue'
print_line ' use <name|index>'
print_line
end
#
# Uses a module.
#
def cmd_use(*args)
if args.length == 0 || args.first == '-h'
cmd_use_help
return false
end
# Divert logic for dangerzone mode
args = dangerzone_codename_to_module(args)
# Try to create an instance of the supplied module name
mod_name = args[0]
# Use a module by search index
index_from_list(@module_search_results, mod_name) do |mod|
return false unless mod && mod.respond_to?(:fullname)
# Module cache object from @module_search_results
mod_name = mod.fullname
end
# See if the supplied module name has already been resolved
mod_resolved = args[1] == true ? true : false
# Ensure we have a reference name and not a path
if mod_name.start_with?('./', 'modules/')
mod_name.sub!(%r{^(?:\./)?modules/}, '')
end
if mod_name.end_with?('.rb')
mod_name.sub!(/\.rb$/, '')
end
begin
mod = framework.modules.create(mod_name)
unless mod
unless mod_resolved
mods_found = cmd_search('-u', mod_name)
end
unless mods_found
print_error("Failed to load module: #{mod_name}")
return false
end
end
rescue Rex::AmbiguousArgumentError => info
print_error(info.to_s)
rescue NameError => info
log_error("The supplied module name is ambiguous: #{$!}.")
end
return false if (mod == nil)
# Enstack the command dispatcher for this module type
dispatcher = nil
case mod.type
when Msf::MODULE_ENCODER
dispatcher = Msf::Ui::Console::CommandDispatcher::Encoder
when Msf::MODULE_EXPLOIT
dispatcher = Msf::Ui::Console::CommandDispatcher::Exploit
when Msf::MODULE_NOP
dispatcher = Msf::Ui::Console::CommandDispatcher::Nop
when Msf::MODULE_PAYLOAD
dispatcher = Msf::Ui::Console::CommandDispatcher::Payload
when Msf::MODULE_AUX
dispatcher = Msf::Ui::Console::CommandDispatcher::Auxiliary
when Msf::MODULE_POST
dispatcher = Msf::Ui::Console::CommandDispatcher::Post
when Msf::MODULE_EVASION
dispatcher = Msf::Ui::Console::CommandDispatcher::Evasion
else
print_error("Unsupported module type: #{mod.type}")
return false
end
# If there's currently an active module, enqueque it and go back
if (active_module)
@previous_module = active_module
cmd_back()
end
if (dispatcher != nil)
driver.enstack_dispatcher(dispatcher)
end
# Update the active module
self.active_module = mod
# If a datastore cache exists for this module, then load it up
if @dscache[active_module.fullname]
active_module.datastore.update(@dscache[active_module.fullname])
end
mod.init_ui(driver.input, driver.output)
end
#
# Command to take to the previously active module
#
def cmd_previous(*args)
if @previous_module
self.cmd_use(@previous_module.fullname)
else
print_error("There isn't a previous module at the moment")
end
end
#
# Help for the 'previous' command
#
def cmd_previous_help
print_line "Usage: previous"
print_line
print_line "Set the previously loaded module as the current module"
print_line
print_line "Previous module: #{@previous_module ? @previous_module.fullname : 'none'}"
print_line
end
#
# Command to enqueque a module on the module stack
#
def cmd_pushm(*args)
# could check if each argument is a valid module, but for now let them hang themselves
if args.count > 0
args.each do |arg|
@module_name_stack.push(arg)
# Note new modules are appended to the array and are only module (full)names
end
else #then just push the active module
if active_module
#print_status "Pushing the active module"
@module_name_stack.push(active_module.fullname)
else
print_error("There isn't an active module and you didn't specify a module to push")
return self.cmd_pushm_help
end
end
end
#
# Tab completion for the pushm command
#
# @param str [String] the string currently being typed before tab was hit
# @param words [Array<String>] the previously completed words on the command line. words is always
# at least 1 when tab completion has reached this stage since the command itself has been completed
def cmd_pushm_tabs(str, words)
tab_complete_module(str, words)
end
#
# Help for the 'pushm' command
#
def cmd_pushm_help
print_line "Usage: pushm [module1 [,module2, module3...]]"
print_line
print_line "push current active module or specified modules onto the module stack"
print_line
end
#
# Command to dequeque a module from the module stack
#
def cmd_popm(*args)
if (args.count > 1 or not args[0].respond_to?("to_i"))
return self.cmd_popm_help
elsif args.count == 1
# then pop 'n' items off the stack, but don't change the active module
if args[0].to_i >= @module_name_stack.count
# in case they pass in a number >= the length of @module_name_stack
@module_name_stack = []
print_status("The module stack is empty")
else
@module_name_stack.pop(args[0].to_i)
end
else #then just pop the array and make that the active module
pop = @module_name_stack.pop
if pop
return self.cmd_use(pop)
else
print_error("There isn't anything to pop, the module stack is empty")
end
end
end
#
# Help for the 'popm' command
#
def cmd_popm_help
print_line "Usage: popm [n]"
print_line
print_line "pop the latest module off of the module stack and make it the active module"
print_line "or pop n modules off the stack, but don't change the active module"
print_line
end
def cmd_listm_help
print_line 'Usage: listm'
print_line
print_line 'List the module stack'
print_line
end
def cmd_listm(*_args)
if @module_name_stack.empty?
print_error('The module stack is empty')
return
end
print_status("Module stack:\n")
@module_name_stack.to_enum.with_index.reverse_each do |name, idx|
print_line("[#{idx}]\t#{name}")
end
end
def cmd_clearm_help
print_line 'Usage: clearm'
print_line
print_line 'Clear the module stack'
print_line
end
def cmd_clearm(*_args)
print_status('Clearing the module stack')
@module_name_stack.clear
end
#
# Tab completion for the use command
#
# @param str [String] the string currently being typed before tab was hit
# @param words [Array<String>] the previously completed words on the command line. words is always
# at least 1 when tab completion has reached this stage since the command itself has been completd
def cmd_use_tabs(str, words)
return [] if words.length > 1
tab_complete_module(str, words)
end
def cmd_reload_all_help
print_line "Usage: reload_all"
print_line
print_line "Reload all modules from all configured module paths. This may take awhile."
print_line "See also: loadpath"
print_line
end
#
# Reload all module paths that we are aware of
#
def cmd_reload_all(*args)
if args.length > 0
cmd_reload_all_help
return
end
print_status("Reloading modules from all module paths...")
framework.modules.reload_modules
log_msg = "Please see #{File.join(Msf::Config.log_directory, 'framework.log')} for details."
# Check for modules that failed to load
if framework.modules.module_load_error_by_path.length > 0
print_error("WARNING! The following modules could not be loaded!")
framework.modules.module_load_error_by_path.each do |path, _error|
print_error("\t#{path}")
end
print_error(log_msg)
end
if framework.modules.module_load_warnings.length > 0
print_warning("The following modules were loaded with warnings:")
framework.modules.module_load_warnings.each do |path, _error|
print_warning("\t#{path}")
end
print_warning(log_msg)
end
self.driver.run_single("banner")
end
def cmd_back_help
print_line "Usage: back"
print_line
print_line "Return to the global dispatcher context"
print_line
end
#
# Pop the current dispatcher stack context, assuming it isn't pointed at
# the core or database backend stack context.
#
def cmd_back(*args)
if (driver.dispatcher_stack.size > 1 and
driver.current_dispatcher.name != 'Core' and
driver.current_dispatcher.name != 'Database Backend')
# Reset the active module if we have one
if (active_module)
# Do NOT reset the UI anymore
# active_module.reset_ui
# Save the module's datastore so that we can load it later
# if the module is used again
@dscache[active_module.fullname] = active_module.datastore.dup
self.active_module = nil
end
# Destack the current dispatcher
driver.destack_dispatcher
end
end
#
# Tab complete module names
#
def tab_complete_module(str, words)
res = []
framework.modules.module_types.each do |mtyp|
mset = framework.modules.module_names(mtyp)
mset.each do |mref|
res << mtyp + '/' + mref
end
end
return dangerzone_modules_to_codenames(res.sort) if dangerzone_active?
return res.sort
end
#
# Convert squirrel names back to regular module names
#
def dangerzone_codename_to_module(args)
return args unless dangerzone_active? && args.length > 0 && args[0].length > 0
return args unless args[0] =~ /^[A-Z]/
args[0] = dangerzone_codename_to_module_name(args[0])
args
end
#
# Determine if dangerzone mode is active via date or environment variable
#
def dangerzone_active?
active = Time.now.strftime("%m%d") == "0401" || Rex::Compat.getenv('DANGERZONE').to_i > 0
if active && @dangerzone_map.nil?
dangerzone_build_map
end
active
end
#
# Convert module names to squirrel names
#
def dangerzone_modules_to_codenames(names)
(names + @dangerzone_map.keys.grep(/^[A-Z]+/)).sort
end
def dangerzone_codename_to_module_name(cname)
@dangerzone_map[cname] || cname
end
def dangerzone_module_name_to_codename(mname)
@dangerzone_map[mname] || mname
end
def dangerzone_build_map
return unless @dangerzone_map.nil?
@dangerzone_map = {}
res = []
%W{exploit auxiliary}.each do |mtyp|
mset = framework.modules.module_names(mtyp)
mset.each do |mref|
res << mtyp + '/' + mref
end
end
words_a = ::File.readlines(::File.join(
::Msf::Config.data_directory, "wordlists", "dangerzone_a.txt"
)).map{|line| line.strip.upcase}
words_b = ::File.readlines(::File.join(
::Msf::Config.data_directory, "wordlists", "dangerzone_b.txt"
)).map{|line| line.strip.upcase}
aidx = -1
bidx = -1
res.sort.each do |mname|
word_a = words_a[ (aidx += 1) % words_a.length ]
word_b = words_b[ (bidx += 1) % words_b.length ]
cname = word_a + word_b
while @dangerzone_map[cname]
aidx += 1
word_a = words_a[ (aidx += 1) % words_a.length ]
cname = word_a + word_b
end
@dangerzone_map[mname] = cname
@dangerzone_map[cname] = mname
end
end
#
# Module list enumeration
#
def show_encoders(regex = nil, minrank = nil, opts = nil) # :nodoc:
# If an active module has been selected and it's an exploit, get the
# list of compatible encoders and display them
if (active_module and active_module.exploit? == true)
show_module_set("Compatible Encoders", active_module.compatible_encoders, regex, minrank, opts)
else
show_module_set("Encoders", framework.encoders, regex, minrank, opts)
end
end
def show_nops(regex = nil, minrank = nil, opts = nil) # :nodoc:
show_module_set("NOP Generators", framework.nops, regex, minrank, opts)
end
def show_exploits(regex = nil, minrank = nil, opts = nil) # :nodoc:
show_module_set("Exploits", framework.exploits, regex, minrank, opts)
end
def show_payloads(regex = nil, minrank = nil, opts = nil) # :nodoc:
# If an active module has been selected and it's an exploit, get the
# list of compatible payloads and display them
if active_module && (active_module.exploit? || active_module.evasion?)
@@payload_show_results = active_module.compatible_payloads
show_module_set('Compatible Payloads', @@payload_show_results, regex, minrank, opts)
else
show_module_set('Payloads', framework.payloads, regex, minrank, opts)
end
end
def show_auxiliary(regex = nil, minrank = nil, opts = nil) # :nodoc:
show_module_set("Auxiliary", framework.auxiliary, regex, minrank, opts)
end
def show_post(regex = nil, minrank = nil, opts = nil) # :nodoc:
show_module_set("Post", framework.post, regex, minrank, opts)
end
def show_missing(mod) # :nodoc:
mod_opt = Serializer::ReadableText.dump_options(mod, ' ', true)
print("\nModule options (#{mod.fullname}):\n\n#{mod_opt}\n") if (mod_opt and mod_opt.length > 0)
# If it's an exploit and a payload is defined, create it and
# display the payload's options
if (mod.exploit? and mod.datastore['PAYLOAD'])
p = framework.payloads.create(mod.datastore['PAYLOAD'])
if (!p)
print_error("Invalid payload defined: #{mod.datastore['PAYLOAD']}\n")
return
end
p.share_datastore(mod.datastore)
if (p)
p_opt = Serializer::ReadableText.dump_options(p, ' ', true)
print("\nPayload options (#{mod.datastore['PAYLOAD']}):\n\n#{p_opt}\n") if (p_opt and p_opt.length > 0)
end
end
end
def show_evasion(regex = nil, minrank = nil, opts = nil) # :nodoc:
show_module_set('evasion', framework.evasion, regex, minrank, opts)
end
def show_global_options
columns = [ 'Option', 'Current Setting', 'Description' ]
tbl = Table.new(
Table::Style::Default,
'Header' => 'Global Options:',
'Prefix' => "\n",
'Postfix' => "\n",
'Columns' => columns
)
[
[ 'ConsoleLogging', framework.datastore['ConsoleLogging'] || "false", 'Log all console input and output' ],
[ 'LogLevel', framework.datastore['LogLevel'] || "0", 'Verbosity of logs (default 0, max 3)' ],
[ 'MinimumRank', framework.datastore['MinimumRank'] || "0", 'The minimum rank of exploits that will run without explicit confirmation' ],
[ 'SessionLogging', framework.datastore['SessionLogging'] || "false", 'Log all input and output for sessions' ],
[ 'TimestampOutput', framework.datastore['TimestampOutput'] || "false", 'Prefix all console output with a timestamp' ],
[ 'Prompt', framework.datastore['Prompt'] || Msf::Ui::Console::Driver::DefaultPrompt.to_s.gsub(/%.../,"") , "The prompt string" ],
[ 'PromptChar', framework.datastore['PromptChar'] || Msf::Ui::Console::Driver::DefaultPromptChar.to_s.gsub(/%.../,""), "The prompt character" ],
[ 'PromptTimeFormat', framework.datastore['PromptTimeFormat'] || Time::DATE_FORMATS[:db].to_s, 'Format for timestamp escapes in prompts' ],
[ 'MeterpreterPrompt', framework.datastore['MeterpreterPrompt'] || '%undmeterpreter%clr', 'The meterpreter prompt string' ],
].each { |r| tbl << r }
print(tbl.to_s)
end
def show_targets(mod) # :nodoc:
case mod
when Msf::Exploit
mod_targs = Serializer::ReadableText.dump_exploit_targets(mod, ' ')
print("\nExploit targets:\n\n#{mod_targs}\n") if (mod_targs and mod_targs.length > 0)
when Msf::Evasion
mod_targs = Serializer::ReadableText.dump_evasion_targets(mod, ' ')
print("\nEvasion targets:\n\n#{mod_targs}\n") if (mod_targs and mod_targs.length > 0)
end
end
def show_actions(mod) # :nodoc:
mod_actions = Serializer::ReadableText.dump_module_actions(mod, ' ')
print("\n#{mod.type.capitalize} actions:\n\n#{mod_actions}\n") if (mod_actions and mod_actions.length > 0)
end
def show_advanced_options(mod) # :nodoc:
mod_opt = Serializer::ReadableText.dump_advanced_options(mod, ' ')
print("\nModule advanced options (#{mod.fullname}):\n\n#{mod_opt}\n") if (mod_opt and mod_opt.length > 0)
# If it's an exploit and a payload is defined, create it and
# display the payload's options
if (mod.exploit? and mod.datastore['PAYLOAD'])
p = framework.payloads.create(mod.datastore['PAYLOAD'])
if (!p)
print_error("Invalid payload defined: #{mod.datastore['PAYLOAD']}\n")
return
end
p.share_datastore(mod.datastore)
if (p)
p_opt = Serializer::ReadableText.dump_advanced_options(p, ' ')
print("\nPayload advanced options (#{mod.datastore['PAYLOAD']}):\n\n#{p_opt}\n") if (p_opt and p_opt.length > 0)
end
end
end
def show_evasion_options(mod) # :nodoc:
mod_opt = Serializer::ReadableText.dump_evasion_options(mod, ' ')
print("\nModule evasion options:\n\n#{mod_opt}\n") if (mod_opt and mod_opt.length > 0)
# If it's an exploit and a payload is defined, create it and
# display the payload's options
if (mod.evasion? and mod.datastore['PAYLOAD'])
p = framework.payloads.create(mod.datastore['PAYLOAD'])
if (!p)
print_error("Invalid payload defined: #{mod.datastore['PAYLOAD']}\n")
return
end
p.share_datastore(mod.datastore)
if (p)
p_opt = Serializer::ReadableText.dump_evasion_options(p, ' ')
print("\nPayload evasion options (#{mod.datastore['PAYLOAD']}):\n\n#{p_opt}\n") if (p_opt and p_opt.length > 0)
end
end
end
def show_plugins # :nodoc:
tbl = Table.new(
Table::Style::Default,
'Header' => 'Loaded Plugins',
'Prefix' => "\n",
'Postfix' => "\n",
'Columns' => [ 'Name', 'Description' ]
)
framework.plugins.each { |plugin|
tbl << [ plugin.name, plugin.desc ]
}
# create an instance of core to call the list_plugins
core = Msf::Ui::Console::CommandDispatcher::Core.new(driver)
core.list_plugins
print(tbl.to_s)
end
def show_module_set(type, module_set, regex = nil, minrank = nil, opts = nil) # :nodoc:
count = -1
tbl = generate_module_table(type)
module_set.sort.each { |refname, mod|
o = nil
begin
o = mod.new
rescue ::Exception
end
next if not o
# handle a search string, search deep
if (
not regex or
o.name.match(regex) or
o.description.match(regex) or
o.refname.match(regex) or
o.references.map{|x| [x.ctx_id + '-' + x.ctx_val, x.to_s]}.join(' ').match(regex) or
o.author.to_s.match(regex)
)
if (not minrank or minrank <= o.rank)
show = true
if opts
mod_opt_keys = o.options.keys.map { |x| x.downcase }
opts.each do |opt,val|
if !mod_opt_keys.include?(opt.downcase) || (val != nil && o.datastore[opt] != val)
show = false
end
end
end
if (opts == nil or show == true)
tbl << [
count += 1,
refname,
o.disclosure_date.nil? ? "" : o.disclosure_date.strftime("%Y-%m-%d"),
o.rank_to_s,
o.has_check? ? 'Yes' : 'No',
o.name
]
end
end
end
}
print(tbl.to_s)
end
def generate_module_table(type, search_term = nil) # :nodoc:
Table.new(
Table::Style::Default,
'Header' => type,
'Prefix' => "\n",
'Postfix' => "\n",
'Columns' => [ '#', 'Name', 'Disclosure Date', 'Rank', 'Check', 'Description' ],
'SearchTerm' => search_term
)
end
end
end
end
end
end
| 36.425926 | 158 | 0.510019 |
610aa5dc5501a94b351b0181814a9e2d4e4c30bd | 4,831 | require_relative "../spec_helper"
begin
require 'tilt/erb'
rescue LoadError
warn "tilt not installed, skipping render_locals plugin test"
else
describe "render_locals plugin with :merge option" do
before do
app(:bare) do
plugin :render_locals, :render=>{:a=>1, :b=>2, :c=>3, :d=>4, :e=>5}, :layout=>{:a=>-1, :f=>6}, :merge=>true
plugin :render, :views=>"./spec/views", :check_paths=>true, :layout_opts=>{:inline=>'<%= a %>|<%= b %>|<%= c %>|<%= d %>|<%= e %>|<%= f %>|<%= yield %>'}
route do |r|
r.on "base" do
view(:inline=>'(<%= a %>|<%= b %>|<%= c %>|<%= d %>|<%= e %>)')
end
r.on "override" do
view(:inline=>'(<%= a %>|<%= b %>|<%= c %>|<%= d %>|<%= e %>)', :locals=>{:b=>-2, :d=>-4, :f=>-6}, :layout_opts=>{:locals=>{:d=>0, :c=>-3, :e=>-5}})
end
r.on "no_merge" do
view(:inline=>'(<%= a %>|<%= b %>|<%= c %>|<%= d %>|<%= e %>)', :locals=>{:b=>-2, :d=>-4, :f=>-6}, :layout_opts=>{:merge_locals=>false, :locals=>{:d=>0, :c=>-3, :e=>-5}})
end
end
end
end
it "should choose method opts before plugin opts, and layout specific before locals" do
body("/base").must_equal '-1|2|3|4|5|6|(1|2|3|4|5)'
body("/override").must_equal '-1|-2|-3|0|-5|-6|(1|-2|3|-4|5)'
body("/no_merge").must_equal '-1|2|-3|0|-5|6|(1|-2|3|-4|5)'
end
end
describe "render_locals plugin" do
it "locals overrides" do
app(:bare) do
plugin :render, :views=>"./spec/views", :layout_opts=>{:template=>'multiple-layout'}
plugin :render_locals, :render=>{:title=>'Home', :b=>'B'}, :layout=>{:title=>'Roda', :a=>'A'}
route do |r|
view("multiple", :locals=>{:b=>"BB"}, :layout_opts=>{:locals=>{:a=>'AA'}})
end
end
body.strip.must_equal "Roda:AA::Home:BB"
end
it ":layout=>true/false/string/hash/not-present respects plugin layout switch and template" do
app(:bare) do
plugin :render, :views=>"./spec/views", :layout_opts=>{:template=>'layout-yield'}
plugin :render_locals, :layout=>{:title=>'a'}
route do |r|
opts = {:content=>'bar'}
opts[:layout] = true if r.path == '/'
opts[:layout] = false if r.path == '/f'
opts[:layout] = 'layout' if r.path == '/s'
opts[:layout] = {:template=>'layout'} if r.path == '/h'
view(opts)
end
end
body.gsub("\n", '').must_equal "HeaderbarFooter"
body('/a').gsub("\n", '').must_equal "HeaderbarFooter"
body('/f').gsub("\n", '').must_equal "bar"
body('/s').gsub("\n", '').must_equal "<title>Roda: a</title>bar"
body('/h').gsub("\n", '').must_equal "<title>Roda: a</title>bar"
app.plugin :render
body.gsub("\n", '').must_equal "HeaderbarFooter"
body('/a').gsub("\n", '').must_equal "HeaderbarFooter"
body('/f').gsub("\n", '').must_equal "bar"
body('/s').gsub("\n", '').must_equal "<title>Roda: a</title>bar"
body('/h').gsub("\n", '').must_equal "<title>Roda: a</title>bar"
app.plugin :render, :layout=>true
body.gsub("\n", '').must_equal "HeaderbarFooter"
body('/a').gsub("\n", '').must_equal "HeaderbarFooter"
body('/f').gsub("\n", '').must_equal "bar"
body('/s').gsub("\n", '').must_equal "<title>Roda: a</title>bar"
body('/h').gsub("\n", '').must_equal "<title>Roda: a</title>bar"
app.plugin :render, :layout=>'layout-alternative'
body.gsub("\n", '').must_equal "<title>Alternative Layout: a</title>bar"
body('/a').gsub("\n", '').must_equal "<title>Alternative Layout: a</title>bar"
body('/f').gsub("\n", '').must_equal "bar"
body('/s').gsub("\n", '').must_equal "<title>Roda: a</title>bar"
body('/h').gsub("\n", '').must_equal "<title>Roda: a</title>bar"
app.plugin :render, :layout=>nil
body.gsub("\n", '').must_equal "HeaderbarFooter"
body('/a').gsub("\n", '').must_equal "bar"
body('/f').gsub("\n", '').must_equal "bar"
body('/s').gsub("\n", '').must_equal "<title>Roda: a</title>bar"
body('/h').gsub("\n", '').must_equal "<title>Roda: a</title>bar"
app.plugin :render, :layout=>false
body.gsub("\n", '').must_equal "HeaderbarFooter"
body('/a').gsub("\n", '').must_equal "bar"
body('/f').gsub("\n", '').must_equal "bar"
body('/s').gsub("\n", '').must_equal "<title>Roda: a</title>bar"
body('/h').gsub("\n", '').must_equal "<title>Roda: a</title>bar"
app.plugin :render, :layout_opts=>{:template=>'layout-alternative'}
app.plugin :render_locals, :layout=>{:title=>'a'}
body.gsub("\n", '').must_equal "<title>Alternative Layout: a</title>bar"
body('/a').gsub("\n", '').must_equal "bar"
body('/f').gsub("\n", '').must_equal "bar"
body('/s').gsub("\n", '').must_equal "<title>Roda: a</title>bar"
body('/h').gsub("\n", '').must_equal "<title>Roda: a</title>bar"
end
end
end
| 42.008696 | 180 | 0.546678 |
877977de268ed24f3d6c93362242f05f66ba78d1 | 1,002 | class Ott < Formula
desc "Tool for writing definitions of programming languages and calculi"
homepage "https://www.cl.cam.ac.uk/~pes20/ott/"
url "https://github.com/ott-lang/ott/archive/0.29.tar.gz"
sha256 "42208e47a9dab3ca89da79c4b1063a728532343a4bf5709393bb3d673a9eaeed"
head "https://github.com/ott-lang/ott.git"
bottle do
cellar :any_skip_relocation
sha256 "61309aafe923d5ff35914516b48adb21ab3d2aa95a317b8d827cde1166e2252e" => :catalina
sha256 "28c5c4755f6e7c34e6ef86009fa839b694ac00136fb822132e38fa06a5361be3" => :mojave
sha256 "ed14bf477139c689eaa93ec2d0fb3c6cc73940a04d194621819f417d18bae033" => :high_sierra
end
depends_on "ocaml" => :build
def install
system "make", "world"
bin.install "bin/ott"
pkgshare.install "examples"
(pkgshare/"emacs/site-lisp/ott").install "emacs/ott-mode.el"
end
test do
system "#{bin}/ott", "-i", pkgshare/"examples/peterson_caml.ott",
"-o", "peterson_caml.tex", "-o", "peterson_caml.v"
end
end
| 34.551724 | 93 | 0.742515 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.